开发者

How to print binary number via printf [duplicate]

This question already has answers here: Closed 11 years ago.

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 p开发者_Python百科rintf?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜