0

If the user inputs a very large number in binary the output shows a 0, how would I go about modifying this function to work with larger numbers?

{ 
    // 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
}
4

1 回答 1

1

停止将您的“二进制数”作为int. int 的大小是有限的;最大值一般在20亿左右,也就是10位数。当您将数字滥用为位时,最多可为您提供 10 bits,相当于 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,那么当您指定基数 2 时,有std::stoi和家族(在 中定义<string>)将为您执行此操作。除非您出于学习目的而重新发明轮子,否则最好使用它们。

std::cout << "Base10: " << std::stoi(myNumberString, 0, 2) << '\n';
于 2013-03-09T17:47:16.053 回答