我可以用printf打印十六进制或八进制数字。是否有格式标签打印为二进制或任意基数?
我正在运行gcc。
printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
printf("%b\n", 10); // prints "%b\n"
我可以用printf打印十六进制或八进制数字。是否有格式标签打印为二进制或任意基数?
我正在运行gcc。
printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
printf("%b\n", 10); // prints "%b\n"
当前回答
简单,经过测试,适用于任何无符号整数类型。没有头痛。
#include <stdint.h>
#include <stdio.h>
// Prints the binary representation of any unsigned integer
// When running, pass 1 to first_call
void printf_binary(unsigned int number, int first_call)
{
if (first_call)
{
printf("The binary representation of %d is [", number);
}
if (number >> 1)
{
printf_binary(number >> 1, 0);
putc((number & 1) ? '1' : '0', stdout);
}
else
{
putc((number & 1) ? '1' : '0', stdout);
}
if (first_call)
{
printf("]\n");
}
}
其他回答
// m specifies how many of the low bits are shown.
// Replace m with sizeof(n) below for all bits and
// remove it from the parameter list if you like.
void print_binary(unsigned long n, unsigned long m) {
static char show[3] = "01";
unsigned long mask = 1ULL << (m-1);
while(mask) {
putchar(show[!!(n&mask)]); mask >>= 1;
}
putchar('\n');
}
使用以下功能:
void conbin(int num){
if(num != 0)
{
conbin(num >> 1);
if (num & 1){
printf("1");
}
else{
printf("0");
}
}
}
可能有点超时,但是如果你只是为了调试来理解或回溯你正在做的一些二进制操作而需要这个,你可以看看wcalc(一个简单的控制台计算器)。使用-b选项可以得到二进制输出。
e.g.
$ wcalc -b "(256 | 3) & 0xff" = 0b11
C标准库中没有这样输出二进制的格式化函数。printf家族支持的所有格式操作都是针对人类可读的文本。
我喜欢的代码由paniq,静态缓冲区是一个好主意。但是,如果你想在一个printf()中有多个二进制格式,它就失败了,因为它总是返回相同的指针并覆盖数组。
下面是一个C风格的下拉列表,它可以在分割缓冲区上旋转指针。
char *
format_binary(unsigned int x)
{
#define MAXLEN 8 // width of output format
#define MAXCNT 4 // count per printf statement
static char fmtbuf[(MAXLEN+1)*MAXCNT];
static int count = 0;
char *b;
count = count % MAXCNT + 1;
b = &fmtbuf[(MAXLEN+1)*count];
b[MAXLEN] = '\0';
for (int z = 0; z < MAXLEN; z++) { b[MAXLEN-1-z] = ((x>>z) & 0x1) ? '1' : '0'; }
return b;
}