C++ 二进制转十进制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27049411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:43:46  来源:igfitidea点击:

C++ Binary to decimal?

c++binarydecimalbase

提问by S?ren Eriksen

I made a function that converts binary numbers to decimals, but if i go to high on the binary numbers, it just returns 256??? What could cause this? I'm using int variables. Any help would be really appreciated

我做了一个将二进制数转换为十进制数的函数,但是如果我对二进制数进行高位,它只会返回 256 ???什么可能导致这种情况?我正在使用 int 变量。任何帮助将非常感激

    #include <iostream>

using namespace std;

int FromBin (int n)
{
    int increment;
    int Result;
    increment = 1;
    Result = 0;
    while(n != 0)
    {
        if (n % 10 == 1){
            Result = Result+increment;
            n = n-1;
        }
        n = n/10;
        increment = increment*2;
    }
    cout<<Result;
}

void ToBin(int n)
{
    if (n / 2 != 0) {
        ToBin(n / 2);
    }
    cout<<n % 2;
}

int main()
{
    int choice;
    int n;
    cout<<"Choose a function: press 0 for decimals to binary, press 1 for binary to decimal\n";
    cin>>choice;
    if (choice == 0){
        cout<<"Enter a number: \n";
        cin>>n;
        ToBin(n);
    }
    else if (choice == 1){
        cout<<"Enter a number: \n";
        cin>>n;
        FromBin(n);
    }
    else{
        cout<<"Invalid input";
    }
}

I'm new to C++ so I don't understand this... :/

我是 C++ 新手,所以我不明白这一点......:/

回答by alexkrause88

This is a cool program you got going on here... This is what I found for a possible solution to your problem...

这是你在这里进行的一个很酷的程序......这是我为你的问题找到的可能解决方案......

 /* C++ program to convert binary number into decimal */
 #include <iostream>
     using namespace std;
 int main()
 {
     long bin, dec = 0, rem, num, base = 1;
     cout << "Enter the binary number(1s and 0s) : ";
     cin >> num;
     bin = num;
     while (num > 0)
     {
         rem = num % 10;
         dec = dec + rem * base;
         base = base * 2;
         num = num / 10;
     }
     cout << "The decimal equivalent of " << bin << " : " << dec << endl;
     return 0;
 }

回答by Cory Kramer

This is what I think you were shooting for. You can handle larger numbers by switching from intto long.

这就是我认为你正在拍摄的。您可以通过从 切换到int来处理更大的数字long

long fromBin(long n)
{
    long factor = 1;
    long total = 0;

    while (n != 0)
    {
        total += (n%10) * factor;
        n /= 10;
        factor *= 2;
    }

    return total;
}

Live demo

现场演示

回答by Tomcatus

From your comment I can see that you are trying to use it on a number that is just too large for an int variable. Look for limits, as for int I found that maximal value is 2147483647.

从您的评论中,我可以看到您正试图在一个对于 int 变量来说太大的数字上使用它。寻找限制,至于 int 我发现最大值是 2147483647。