Reputation: 143
If the string is "8123", I first converted the string number into its integer form 8123 and then sent this number to a function that converts it to binary. I got numbers as big as unsigned long long to work but once its passed that, the outputs are wrong. Is there a way to convert to binary by looking at each digit. i.e looking a the 3, 2, 1, and 8 to convert to binary.
So rather than taking the string "999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999" and turning it into a number, is there a way to look at each character in this string and turn it into binary?
Any suggestions is much appreciated
Upvotes: 2
Views: 404
Reputation: 45654
string dec2bin(string in) {
for(size_t i = 0; i < in.length(); i++)
in[i] -= '0';
string out;
while(in.length()) {
out.insert(0, 1, '0' + (in[in.length()-1]&1));
char overflow = 0;
if(in[0]<=1) {
overflow = 10;
in.erase(0);
}
for(size_t i = 0; i<in.length(); i++) {
in[i] += overflow;
overflow = 10 * (in[i]&1);
in[i] /= 2;
}
}
return out;
}
Upvotes: 1
Reputation: 2429
Pseudocode:
string binary_string = ""
#an example
number = 81
while (number != 0)
#append the string casted value of the remainder of (number / 2)
#to the front of binary_string
binary_string = str(number % 2) + binary_string
number = number / 2
e.g. 81:
binary_string = str(81 % 2) + binary_string = str(1) + "" = "1"
number = 81 / 2 = 40
binary_string = str(40 % 2) + binary_string = str(0) + "1" = "01"
number = 40 / 2 = 20
binary_string = str(20 % 2) + binary_string = str(0) + "01" = "001"
number = 20 / 2 = 10
binary_string = str(10 % 2) + binary_string = str(0) + "001" = "0001"
number = 10 / 2 = 5
binary_string = str(5 % 2) + binary_string = str(1) + "0001" = "10001"
number = 5 / 2 = 2
binary_string = str(2 % 2) + binary_string = str(0) + "10001" = "010001"
number = 2 / 2 = 1
binary_string = str(1 % 2) + binary_string = str(1) + "010001" = "1010001"
81 -> "1010001"
Upvotes: 1