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.

C++ doesn't have a long long type. You're relying on compiler extensions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.