954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Binary (12 digit max) to Decimal/Integer

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.

danbellinger1
Newbie Poster
9 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

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

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You