Base2 到 Base10 转换器不适用于非常大的数字?

Base2 to Base10 converter won't work with very large numbers?

本文关键字:数字 非常 适用于 Base10 转换器 不适用 Base2      更新时间:2023-10-16

如果用户输入一个非常大的二进制数,输出显示一个0,我该如何修改这个函数来处理更大的数字呢?

{ 
    // Binary to Decimal converter function
    int bin_Dec(int myInteger)
    {
    int output = 0;
    for(int index=0; myInteger > 0; index++ )
    {
    if(myInteger %10 == 1)
        {
            output += pow(2, index); 
        }
    myInteger /= 10;
    }
    return output;
    }
    int _tmain(int argc, _TCHAR* argv[])
    { // start main
    int myNumber;
    // get number from user
    cout << "Enter a binary number, Base2: "; // ask for number 
    cin >> myNumber;
    //print conversion
    cout << "Base10: " << bin_Dec(myNumber) << endl; // print conversion
    system("pause");
    } // end of main
}

停止将您的"二进制数"作为int。int型在大小上是有限的;最大值一般在20亿左右,也就是10位数。当你把数字当作位滥用时,你得到的最大值是10 ,等于1023。

string代替。你没有对输入做任何有用的数学运算;你只是把它当作一串数字。

// oh, and unless you have good reason...this would be better unsigned.
// Otherwise your computer might catch fire when you specify a number larger
// than INT_MAX.  With an unsigned int, it's guaranteed to just lop off the
// high bits.
// (I may be overstating the "catch fire" part.  But the behavior is undefined.)
unsigned int bin_to_dec(std::string const &n) {
    unsigned int result = 0;
    for (auto it = n.begin(); it != n.end(); ++it) {
        result <<= 1;
        if (*it == '1') result |= 1;
    }
    return result;
}

如果你有c++ 11,有std::stoi和家族(在<string>中定义),当你指定基数2时,它们会为你做这些。除非你是为了学习而重新发明轮子,否则最好使用它们。

std::cout << "Base10: " << std::stoi(myNumberString, 0, 2) << 'n';