Search code examples
c++binarydecimalradix

C++ Binary to decimal?


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


Solution

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