How to print binary number via printf [duplicate] How to print binary number via printf [duplicate] c c

How to print binary number via printf [duplicate]


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");


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);

Here's the origin:

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.