简体   繁体   中英

Converting decimal to binary in C

The code is giving false answers. İf number equals 42, it turns it to 101010. Ok, it is true. But if number equals 4, it turns it to 99. I didn't find the mistake. How can i fix the code?

#include<stdio.h>
#include<conio.h>
#include<math.h>

int main()
{
    int i,digit,number=4;
    long long bin= 0LL;
    i=0;
    while(number>0)   
    {
          digit=number%2;
          bin+=digit*(int)pow(10,i);
          number/=2;
          i++;
    }
    printf("%d ",bin);
    getch();   
}

Stop using floating point calculations for this. You are subject to the vagaries of floating point. When I ran your program with my compiler, the output was 100. But I guess your compiler treated the floating point pow differently.

A simple change to make the code behave, and use integer arithmetic only, would be like this:

#include<stdio.h>
#include<conio.h>
#include<math.h>

int main()
{
    int digit,number=4;
    long long scale,bin= 0LL;
    scale=1;
    while(number>0)   
    {
          digit=number%2;
          bin+=digit*scale;
          number/=2;
          scale*=10;
    }
    printf("%lld ",bin);
    getch();   
}

But I'd rather see the binary built up in a string rather than an integer.

You can use a simpler and easier approach to convert decimal to binary number system .

#include <stdio.h>  

int main()  
{  
    long long decimal, tempDecimal, binary;  
    int rem, place = 1;  

    binary = 0;  

    /* 
     * Reads decimal number from user 
     */  
    printf("Enter any decimal number: ");  
    scanf("%lld", &decimal);  
    tempDecimal = decimal;  

    /* 
     * Converts the decimal number to binary number 
     */  
    while(tempDecimal!=0)  
    {  
        rem = tempDecimal % 2;  

        binary = (rem * place) + binary;  

        tempDecimal /= 2;  
        place *= 10;  
    }  

    printf("\nDecimal number = %lld\n", decimal);  
    printf("Binary number = %lld", binary);  

    return 0;  
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM