55

Possible Duplicate:
Is there a printf converter to print in binary format?

Here is my program

#include<stdio.h>
int main ()
{
    int i,a=2;
    i=~a;
    printf("a=%d\ni=%d\n",a,i);

    return 0;
}

The output is

a=2
i=-3

I want this to print in binary. There are...

  • %x (hexadecimal)
  • %o (octal)
  • %d (decimal)

...but what is for printing binary in printf?

8
  • 6
    stackoverflow.com/questions/111928/… Commented Jun 16, 2011 at 13:58
  • 2
    Do you really want binary? Hexadecimal is often just as good (or even better), as it maps every 4 bits into one hex-digit, giving you both a compact and expressive representation of the binary data. Commented Jun 16, 2011 at 14:01
  • 3
    @Kerrek are you really saying that seeing a number in it's binary representation is useless? Try analyzing a float number in hex digits :P Commented Jun 16, 2011 at 14:19
  • 2
    @hexa: Yep, doing that all the time. I wrote a ULP comparer for long doubles, which I gladly debugged in hex. Hex really is just binary compressed a little. Commented Jun 16, 2011 at 14:22
  • 2
    binary can be useful for looking at how bitwise memory maps are set, if they are documented accordingly and you want to look at the values laid out the same way as in the document. lets not bust anyone's chops for wanting their data in whatever format suits their needs most. Commented Sep 4, 2019 at 21:30

2 Answers 2

61

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");
Sign up to request clarification or add additional context in comments.

9 Comments

This prints the binary representation backwards
@David Heffernan How can we write which support both plateform 32bit and 64bit.
@hexa make function & use recursion to correct the printing order.will it be helpful?
@kapilddit - why in the world would you try to add your answer to Hexa's answer? You've been around long enough to know how Stack Overflow works.
Corrected via recursion stackoverflow.com/a/27627015/1079110.
|
54

Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:

char buffer[33];
itoa(i, buffer, 2);
printf("binary: %s\n", buffer);

Source: itoa() in cplusplus reference

It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.

1 Comment

in case <stdlib.h>/<cstdlib> is not working for you, here's a quick roll-your-own implementation @ strudel.org.uk/itoa

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.