C语言如何打印变量的二进制?
分享一个简单的在C中打印二进制的方法。
代码如下:
#include <stdio.h>
void print_b(void *pointer, size_t size){
unsigned long data = *((unsigned long*)pointer);
int length = size*8;
int counter = 0;
printf("十进制: %lu\n", data);
printf("二进制: ");
while(length-->0){
printf("%lu", (data>>length)&0x1);
counter++;
if(counter%8==0){
printf(" ");
}
}
}
具体例子:
int main()
{
int x = 10;
print_b(&x, sizeof(x));
return 0;
}
十进制: 10
二进制: 00000000 00000000 00000000 00001010