[英]Convert String (binary) to Integer
I am writing a program where the input data (in binary) is split into half and convert to integer to perform some calculation. 我正在编写一个程序,将输入数据(二进制)分为两半,然后转换为整数以执行一些计算。 So I:
所以我:
Accept binary input and store as "String"
接受二进制输入并存储为“字符串”
Split string (note: to be treated as binary) into half and convert to int and store in x and y
将字符串(注意:被视为二进制)拆分为一半,然后转换为int并存储在x和y中
So far i have written step 1. 到目前为止,我已经编写了步骤1。
int main() {
string input;
cout << "Enter data:";
getline(cin, input);
int n = input.size();
int n1 = n/2;
string a, b;
a = input.substr(0,n1);
b = input.substr(n1);
cout << "a: " << a;
cout << "b: " << b;
}
Would like to know how to achieve step 2. Thanks in advance. 想知道如何实现步骤2。在此先感谢。
You can try this: 您可以尝试以下方法:
if(a.length() <= sizeof(unsigned int) * 8) {
unsigned x = 0;
for(int i = 0; i < a.length(); i++) {
x <<= 1; // shift byt 1 to the right
if(a[i] == '1')
x |= 1; // set the bit
else if(a[i] != '0') {
cout << "Attention: Invalid input: " << a[i] << endl;
break;
}
}
cout << "Result is " << x << endl;
}
else cout << "Input too long for an int" << endl;
It uses 它用
<<
, to move the binary bits, when you go right in the ascii string; <<
,以移动二进制位; |
|
for setting the bits. int bin2dec(char* str) {
int n = 0;
int size = strlen(str) - 1;
int count = 0;
while ( *str != '\0' ) {
if ( *str == '1' )
n = n + pow(2, size - count );
count++;
str++;
}
return n;
}
int main() {
char* bin_str = "1100100";
cout << bin2dec(bin_str) << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.