0

I have been trying to get this Binary to Decimal program to work. I'm sure I'm not doing this with the least amount of code, if you have suggestions (using modulus especially).

The errors I used to get was binNum is too large for the "long" type. I then used a "literal" suffix ("LL" in the second function) on the larger numbers. It worked on my laptop, but I transfered it to a linux server and started getting 59098389350228496 when I input 111. I cannot figure out why. Below is the code as it stands now.

#include <iostream>
using namespace std;

long long int binConverter ( long long int binNum );

int main()
{

	long long int  foo;
	
	system("clear");
	
    cout << "Enter a binary number and I will convert it for you: " << flush;
    cin >> foo;
    cout << binConverter(foo) << "::" << foo << "\n";
    
    cin >> foo;

}

long long int binConverter( long long int binNum )
{
 
    long long int result; 
    
    if ( binNum >= 100000000000LL )
    {
         result += 2048;         
         binNum -= 100000000000LL;
    }
    
    if ( binNum >= 10000000000LL )
    {
         result += 1024;
         binNum -= 10000000000LL;
    }
    
    if ( binNum >= 1000000000 )
    {
         result += 512;
         binNum -= 1000000000;
    }
    
    if ( binNum >= 100000000 )
    {
         result += 256;
         binNum -= 100000000;
    }
    
    if ( binNum >= 10000000 )
    {
         result += 128;
         binNum -= 10000000;
    }
    
    if ( binNum >= 1000000 )
    {
         result += 64;
         binNum -= 1000000;
    }
    
    if ( binNum >= 100000 )
    {
         result += 32;
         binNum -= 100000;
    }
    
    if ( binNum >= 10000 )
    {
         result += 16;
         binNum -= 10000;
    }
    
    if ( binNum >= 1000 )
    {
         result += 8;
         binNum -= 1000;
    }
    
    if ( binNum >= 100 )
    {
         result += 4;
         binNum -= 100;
    }

    if ( binNum >= 10 )
    {
         result += 2;
         binNum -= 10;
    }
    
    if ( binNum >= 1 )
    {
         result += 1;
         binNum -= 10;
    }
    
    return result;
    
}

Any help will be appreciated.

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Narue
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.