Home > Software design >  Decimal to Binary Converting Years in C
Decimal to Binary Converting Years in C

Time:11-15

I wrote a program that converts decimal numbers (date of birth) to binary. Converting the day and month works smoothly, but when it comes to converting the year a problem occurs, for example 2001 is converted to 2521075409 instead of 11111010001. Could you tell me where the problem is?

{
    int i;
    long long temp, bin;

    i = 1;
    bin = 0;
    
    printf("Number %d in binary: \n", year);
    while (year > 0) {
        temp = year % 2;            
        year /= 2;              
        bin  = temp * i;        
        i *= 10;                
    }
    printf("%lld\n\n",bin);
}

CodePudding user response:

With int i;, i *= 10 quickly reaches the max limit for 32-bit integer 0x7fff'ffff. So i will also need to be 64-bit, it can be unsigned so the ceiling is a bit higher at 0xffff'ffff'ffff'ffff. Example

unsigned long long i = 1;
unsigned long long bin = 0;
int year = 2001;
while (year > 0) 
{
    int temp = year % 2;
    year /= 2;
    bin  = temp * i;
    i *= 10;
    printf("check i: %llu\n", i);
}
printf("6llu\n\n", bin);

To print larger numbers use a character buffer to save temp in each iteration.

CodePudding user response:

  Alternatively my program use the std::bitset class from the STL library. bitset represents a fixed-size sequence of N bits, and have multiple built-in methods:

string s = bitset<64>(2001).to_string();
     
// Strip off the leading zeroes.
const auto loc1 = s.find('1');
     
if(loc1 != string::npos) s= s.substr(loc1);

cout<<s<<endl; 

output:

11111010001

  full example

  • Related