1

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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
NewCoder
  • 11
  • 3
  • 2
    I recommend you use bitwise operations instead. Get the top bit using bitwise AN, and print it. Then shift the value up one bit and so on. – Some programmer dude Nov 25 '22 at 16:52
  • 2
    Using `pow` for integer math is usually a bad sign. – Retired Ninja Nov 25 '22 at 16:52
  • 1
    Also, when dealing with bits I really recommend you use unsigned integers. – Some programmer dude Nov 25 '22 at 16:52
  • print a, n and b at the end of the for loop (right after `b=b+(pow(10,i)*a);`) and you'll understand what happens. Or better, use a debugger. But anyway as already mentioned, using floating point math and `pow` is wrong to begin with. – Jabberwocky Nov 25 '22 at 16:54
  • 1
    To convert a decimal number to binary, a simple `b = d;` suffices. (More to the point, `d` was binary already, if it has a meaningful base at all.) If you want to construct the binary representation of an integer, don't construct it in an integer. You want it as a *string*. The first decimal number I tried your code on was 1234, and it converted it to -2147483648, which is not the correct binary representation. – Steve Summit Nov 25 '22 at 17:01
  • 1
    [cannot reproduce](https://godbolt.org/z/sqfWM36e5) – n. m. could be an AI Nov 25 '22 at 17:04
  • 1
    @n.m. The OP is probably using a system with a `pow()` that performs poorly on integer powers. – Steve Summit Nov 25 '22 at 17:07
  • @SteveSummit I am using VS Code as my editor how can i fix this? – NewCoder Nov 25 '22 at 17:18
  • @NewCoder the editor you're using is irrelevant. If you want to know what's going on in your code, do what I suggested in my previous comment. If you still don't understand, tell us what output you get, then we can help. – Jabberwocky Nov 25 '22 at 17:26
  • @NewCoder The very simplest fix (although it leaves a number of other potential problems unaddressed) would probably be to change `b=b+(pow(10,i)*a)` to `b=b+(round(pow(10,i))*a)`. – Steve Summit Nov 25 '22 at 17:32
  • 1
    But "decimal coded binary" is a terrible representation. In typical environments, your code as shown will not be able to convert numbers greater than 1023. – Steve Summit Nov 25 '22 at 17:35

2 Answers2

1

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.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

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);
}
Ashish Neupane
  • 193
  • 2
  • 17
  • 2
    Although the code worked for you, it is poor code. It might seem to work, but not for the right reasons. It is not guaranteed to work. Its usage of the problematic `pow()` function, though superficially attractive, is a potentially-fatal limitation. – Steve Summit Nov 25 '22 at 17:41
  • 1
    And to illustrate another of this code's problems, try using it to convert the number 12345, or even just 1234. You probably won't get `11000000111001` and `10011010010`. – Steve Summit Nov 25 '22 at 17:42
  • @SteveSummit I understand where you are coming from. But keeping in mind that the user is trying to figure out why their code is not working with numbers like 4 and 5, you cannot just blame the pow() function here. It is completely irrelevant. – Ashish Neupane Nov 25 '22 at 17:48
  • 1
    On the contrary. The OP's problems with numbers like 4 and 5 are *precisely* because of his system's version of `pow()`. It's doing things like computing `pow(10, 2)` as 99.999999999999985. – Steve Summit Nov 25 '22 at 17:55
  • @SteveSummit Seems like we can answer this in both ways. We can either blame the function or certain compilers. I admit the unusual behavior of pow() function, hence I have updated my answer. Thank you for your input. – Ashish Neupane Nov 25 '22 at 18:32