【问题标题】:Convert String (binary) to Integer将字符串(二进制)转换为整数
【发布时间】:2015-07-28 00:23:11
【问题描述】:

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

  1. 接受二进制输入并存储为“字符串”

  2. 将字符串(注意:被视为二进制)分成两半并转换为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 步。 提前致谢。

【问题讨论】:

  • @Nolane 您的评论有何相关性?问题是关于二进制格式,而atoi“[...] 采用可选的初始加号或减号,后跟尽可能多的 base-10 数字 [...]”。至于问题 - 我们不在这里解决家庭作业。阅读此内容:en.wikipedia.org/wiki/Binary_number#Decimal,然后实施。它是 CS 中最基本的算法之一。
  • 与家庭作业相关的问题都可以,只要您不是简单地要求我们为您完成一个步骤。只需重新考虑您的问题,更具体地询问您在第 2 步中遇到的问题,并确保包含您迄今为止尝试过的内容。
  • @DanBeaulieu 这不是家庭作业。我只是在尝试一些东西,是的,我会自己做。绝不要求任何人轻松向我提供完整的代码。
  • @MateuszGrzejek 感谢您的链接。我正在尝试实施。

标签: c++ string binary


【解决方案1】:

你可以试试这个:

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; 

它使用

  • shift left&lt;&lt;,移动二进制位,当你在 ascii 字符串中向右移动时;
  • binary or | 用于设置位。

【讨论】:

    【解决方案2】:
    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      • 2017-04-25
      • 1970-01-01
      • 2021-02-24
      相关资源
      最近更新 更多