将字符串(二进制)转换为整数

Convert String (binary) to Integer

本文关键字:转换 整数 二进制 字符串      更新时间:2023-10-16

我正在编写一个程序,其中输入数据(二进制)被分成两半并转换为整数以执行一些计算。所以我:

  1. 接受二进制输入并存储为"String"

  2. 将字符串(注意:将作为二进制处理)分成两半并转换为整型并存储在x和y中

到目前为止,我已经写了第一步。

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;
}

想知道如何实现第二步。提前感谢。

你可以试试:

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字符串右移;
  • 二进制或|设置位。
int bin2dec(char* str) {
 int n = 0;
 int size = strlen(str) - 1;
        int count = 0;
 while ( *str != '' ) {
  if ( *str == '1' ) 
      n = n + pow(2, size - count );
  count++; 
  str++;
 }
 return n;
}
int main() {
 char* bin_str = "1100100";
 cout << bin2dec(bin_str) << endl;
}