How to print binary number via printf [duplicate]

2019-01-08 11:01发布

问题:

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, %o, and %d which are for hexadecimal, octal, and decimal number, but what is for printing binary in printf?

回答1:

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


回答2:

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.



标签: c binary printf