C语言 如何通过printf打印二进制数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6373093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:56:11  来源:igfitidea点击:

How to print binary number via printf

cbinaryprintf

提问by Registered User

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

可能的重复:
是否有 printf 转换器以二进制格式打印?

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?

我希望这个以二进制打印。有 %x、%o 和 %d 分别用于十六进制、八进制和十进制数,但是在 printf 中打印二进制是什么?

回答by Vinicius Kamakura

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

printf() 不直接支持。相反,您必须创建自己的函数。

Something like:

就像是:

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

    n >>= 1;
}
printf("\n");

回答by zw324

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

尽管 ANSI C 没有这种机制,但可以使用 itoa() 作为快捷方式:

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

Here's the origin:

这是起源:

itoa in cplusplus reference

cplusplus 中的 itoa 参考

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,但K&R在C书中提到了实现,所以它应该是很常见的。它应该在 stdlib.h 中。