2015-04-01 114 views
-3

例如0x19是二进制的00011001。我试过使用printf%08x,但是这给了我00000019作为输出。我怎样才能打印00011001呢?如何打印十六进制的二进制文件?

+3

写下你自己的功能。 – haccks 2015-04-01 16:52:46

+1

使用[itoa,utoa](http://manpages.ubuntu.com/manpages/utopic/en/man3/itoa.3avr.html)(非标准) 'char bits [32 + 1]; (“%s \ n”,itoa(0x19,bits,2));' – BLUEPIXY 2015-04-01 17:14:41

+0

http://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-二进制格式 – BLUEPIXY 2015-04-01 17:38:15

回答

2
for (i=0; i<32; i++) putchar((x&(1<<(31-i)))?'1':'0'); 
0

如果itoa(非标准功能)可以使用的环境,可写成如下。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <limits.h> 

int main(void){ 
    char bits[CHAR_BIT*sizeof(unsigned)+1]; 
    itoa((int)0x19, bits, 2); 
    int len = strlen(bits); 
    if(len < 8)//%08 
     printf("%0*d%s\n", 8-len, 0, bits); 
    else 
     printf("%s\n", bits); 
    return 0; 
}