我正在编写一个程序,其中输入数据(二进制)被拆分为一半并转换为整数以执行某些计算。 所以我:
接受二进制输入并存储为"字符串"
- 醇>
拆分字符串(注意:将被视为二进制)为一半并转换为int并存储在x和y中
到目前为止,我已经写了第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;
}
想知道如何实现第2步。 提前致谢。
答案 0 :(得分:2)
你可以试试这个:
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;
使用
<<
,当您在ascii字符串中右移时移动二进制位; |
用于设置位。 答案 1 :(得分:0)
{{1}}