C++ Binary to decimal?

40,098

Solution 1

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;
 }

Solution 2

This is what I think you were shooting for. You can handle larger numbers by switching from int to 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

Share:
40,098
Søren Eriksen
Author by

Søren Eriksen

Developing awesome automation software at The LEGO Group

Updated on November 21, 2020

Comments

  • Søren Eriksen
    Søren Eriksen over 3 years

    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

        #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... :/

  • indiv
    indiv over 9 years
    ... on a 64-bit platform.