我可以用printf打印十六进制或八进制数字。是否有格式标签打印为二进制或任意基数?

我正在运行gcc。

printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
printf("%b\n", 10); // prints "%b\n"

当前回答

void print_ulong_bin(const unsigned long * const var, int bits) {
        int i;

        #if defined(__LP64__) || defined(_LP64)
                if( (bits > 64) || (bits <= 0) )
        #else
                if( (bits > 32) || (bits <= 0) )
        #endif
                return;

        for(i = 0; i < bits; i++) { 
                printf("%lu", (*var >> (bits - 1 - i)) & 0x01);
        }
}

应该工作-未经测试。

其他回答

还有一种想法是将数字转换为十六进制格式,然后将每个十六进制密码解码为四个“位”(1和0)。Sprintf可以为我们做位操作:

const char* binary(int n) {
  static const char binnums[16][5] = { "0000","0001","0010","0011",
    "0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111" };
  static const char* hexnums = "0123456789abcdef";
  static char inbuffer[16], outbuffer[4*16];
  const char *i;
  sprintf(inbuffer,"%x",n); // hexadecimal n -> inbuffer
  for(i=inbuffer; *i!=0; ++i) { // for each hexadecimal cipher
    int d = strchr(hexnums,*i) - hexnums; // store its decimal value to d
    char* o = outbuffer+(i-inbuffer)*4; // shift four characters in outbuffer
    sprintf(o,"%s",binnums[d]); // place binary value of d there
  }
  return strchr(outbuffer,'1'); // omit leading zeros
}

puts(binary(42)); // outputs 101010

C标准库中没有这样输出二进制的格式化函数。printf家族支持的所有格式操作都是针对人类可读的文本。

A small utility function in C to do this while solving a bit manipulation problem. This goes over the string checking each set bit using a mask (1< void printStringAsBinary(char * input) { char * temp = input; int i = 7, j =0;; int inputLen = strlen(input); /* Go over the string, check first bit..bit by bit and print 1 or 0 **/ for (j = 0; j < inputLen; j++) { printf("\n"); while (i>=0) { if (*temp & (1 << i)) { printf("1"); } else { printf("0"); } i--; } temp = temp+1; i = 7; printf("\n"); } }

截至2022年2月3日,GNU C库已更新至2.35版。因此,现在支持%b以二进制格式输出。

的输出现在支持%b格式的printf系列函数 二进制整数,如ISO C2X草案中指定的,以及%B变体 采用ISO C2X草案建议的格式。

打印最低有效位并向右移出。这样做直到整数变为零,打印的二进制表示没有前导零,但顺序相反。使用递归,可以很容易地纠正顺序。

#include <stdio.h>

void print_binary(unsigned int number)
{
    if (number >> 1) {
        print_binary(number >> 1);
    }
    putc((number & 1) ? '1' : '0', stdout);
}

对我来说,这是最干净的解决方案之一。如果您喜欢0b前缀和一个尾随的新行字符,我建议对函数进行包装。

在线演示