Base 2到​​Base 10转换器不能用于非常大的数字?

时间:2013-03-09 17:32:18

标签: c++ visual-studio-2012 binary decimal

如果用户输入一个非常大的二进制数字,输出显示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
}

1 个答案:

答案 0 :(得分:1)

停止将您的“二进制数”作为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';