convert integer to 32-bit binary in c

14,923

You compute digits starting from the right, which is why your output shows the right-most digit first. Here is a way that starts from the left, using a bitmask, and does not convert your value to unsigned which may change the bits:

#include <stdio.h>
#include <limits.h>

int main()
{
    long number;
    if ( 1 != scanf("%ld", &number) )
        return 1;

    // sign bit  (cannot use 1L left-shift as that causes UB)
    putchar( '0' + (number < 0) );

    // value bits
    for (long bit = 1L << (CHAR_BIT * sizeof number - 2); bit; bit >>= 1)
        putchar( '0' + !!(number & bit) );

    putchar('\n');
}
Share:
14,923

Related videos on Youtube

naomi88
Author by

naomi88

Updated on September 14, 2022

Comments

  • naomi88
    naomi88 over 1 year

    I'm writing a program to convert an integer to 32-bit binary. The problem is with the output - it comes backwards.

    #include <stdio.h>
    
    int main() {
        long number, binary, num2;
    
        printf("Enter an integer: ");
        scanf("%ld", &number);
    
        for (num2 = (number * 2) / 2; num2 > 0; num2 /= 2) {
            binary = num2 % 2;
            printf("%ld", binary);
        }
        putchar('\n');
        return 0;
    }
    

    So if I put '6' it shows as 011 and it has to be 110

    Also, how do I output the rest of '0's? So that the whole output in this case would be:

    00000000 00000000 00000000 00000110 
    
    • Mitch Wheat
      Mitch Wheat about 9 years
      Also, I typed your question title into a search engine, and unsurprisingly there were many hits!
  • M.M
    M.M about 9 years
    You do avoid UB; however (long)((unsigned long)(number) <<= 1) is implementation-defined which may raise a signal.
  • Weather Vane
    Weather Vane about 9 years
    @MattMcNabb my first solution was to assign the long to, and work with unsigned long throughout, but the explanation was harder to phrase.
  • Weather Vane
    Weather Vane about 9 years
    @MattMcNabb ah, just spotted the incorrect <<= and edited it out, thank you.
  • M.M
    M.M about 9 years
    Hmm we both had the same blind spot, I mean that the << version causes implementation-defined behaviour which may raise a signal. (The <<= version was ill-formed). I suppose this algorithm just has to rely on the implementation being "sensible" with its decision there.
  • corecase
    corecase about 7 years
    Nice! There's just a small problem, this will print the value in reverse bit order. You might want to switch it up to tail recursion to print in the same bit order as the original value... :)
  • R Sahu
    R Sahu about 7 years
    @corecase, it prints the high order bits first. Does that not make more sense?
  • corecase
    corecase about 7 years
    Assuming a typical host machine, the bit order is usually little endian, so the most significant bits tend to be the left-most bits. I would personally prefer to print out the bits in the same order that they are actually represented on my machine, so this would be in reverse of that order... It's kind of a preference thing and it also depends on the endianness of the machine you're running the code on, but based on the context of this question little endian seems like a more reasonable assumption. It is a pretty minor detail though!
  • chqrlie
    chqrlie over 4 years
    You should use '0' instead of hard coding the ASCII value 48. Furthermore you should avoid the non portable gcc extension [0 ... 31]. Finally, binary[31 - i] = number % 2 does not produce a digit value, you must add '0'.