Home > Software engineering >  Decimal To Binary Conversion in C using For
Decimal To Binary Conversion in C using For

Time:11-26

I am not able to convert from decimal to binary in C.Everytime I get a output which is one less than the desired output.For ex.:5 should be 101 but shows up as 100 or 4 should be 100 but shows up as 99.

#include<stdio.h>
#include<math.h>
void main() {
    int a,b=0;
    int n;
    printf("Enter a Decimal Number\n");
    scanf("%d",&n);
    for(int i=0;n>0;i  ) {
        a=n%2;
        n=n/2;
        b=b (pow(10,i)*a);
    }
    printf("%d",b);
}

My output is always one less than the correct answer and I dont know why.It fixes the problem if take b as 1 instead of 0 in the beginning but i dont know why.Please Help.I have just started C a few days ago.

CodePudding user response:

pow is a floating-point function; it takes a double argument and returns a double value. In the C implementation you are using, pow is badly implemented. It does not always produce a correct result even when the correct result is exactly representable. Stop using it for integer arithmetic.

Rewrite the code to compute the desired power of ten using integer arithmetic.

Also, do not compute binary numerals by encoding them a decimal within a int type. It is wasteful and quickly runs into bounds of the type. Use either bits within an unsigned type or an array of char. When scanf("%d",&n); executes, it converts the input string into binary and stores that in n. So n is already binary; you do not need to decode it. Use a loop to find its highest set bit. Then use another loop to print each bit from that position down to the least significant bit.

CodePudding user response:

This code seems fine. I quickly tested it on an online compiler and it seems to be working okay.

I am very sure it has to do with different versions of compilers. compiler which I tested your code in: https://www.onlinegdb.com/online_c_compiler

Edit:

pow() function is not reliable when used with integers since the integer you pass into it as parameter is implicitly converted into data type of double and returns double as output. When you stuff this value into the integer again, it drops the decimal values. Some compilers seem to produce "correct" result with their version of pow() while some don't.

Instead, you can use a different approach to solve your decimal to binary conversion without errors in general use:

#include<stdio.h>
void main() {
    int remainder,result = 0,multiplier = 1;
    int input;
    printf("Enter a Decimal Number\n");
    scanf("%d",&input);
    while(input){
        remainder = input%2;
        result = remainder*multiplier   result;
        multiplier*=10;
        input/=2;
    }
    printf("The binary version of the decimal value is: %d",result);
}
  • Related