如果字符串是" 8123",我首先将字符串编号转换为整数形式8123,然后将此编号发送到将其转换为二进制的函数。我得到的数字和unsigned long long一样大,但是一旦它通过了,输出就错了。有没有办法通过查看每个数字转换为二进制。 即查看3,2,1和8以转换为二进制。
因此,而不是采取字符串" 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"并将其转换为数字,有没有办法查看此字符串中的每个字符并将其转换为二进制文件?
非常感谢任何建议
答案 0 :(得分:1)
伪代码:
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”
答案 1 :(得分:1)
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;
}