我可以用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"
当前回答
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"); } }
其他回答
没有标准和便携的方式。
有些实现提供了itoa(),但大多数实现中都没有,而且它的接口有些糟糕。但是代码在链接后面,应该可以让您非常容易地实现自己的格式化程序。
// 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');
}
还有一种用二进制打印的方法:先转换整数。
要以二进制格式打印6,请将6改为110,然后打印“110”。
绕过char buf[]问题。 printf()格式说明符,标志和字段,如“%08lu”,“%*lX”仍然可用。 不仅是二进制(以2为基数),这种方法还可以扩展到其他以16为基数的基数。 仅限于较小的整数值。
#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>
unsigned long char_to_bin10(char ch) {
unsigned char uch = ch;
unsigned long sum = 0;
unsigned long power = 1;
while (uch) {
if (uch & 1) {
sum += power;
}
power *= 10;
uch /= 2;
}
return sum;
}
uint64_t uint16_to_bin16(uint16_t u) {
uint64_t sum = 0;
uint64_t power = 1;
while (u) {
if (u & 1) {
sum += power;
}
power *= 16;
u /= 2;
}
return sum;
}
void test(void) {
printf("%lu\n", char_to_bin10(0xF1));
// 11110001
printf("%" PRIX64 "\n", uint16_to_bin16(0xF731));
// 1111011100110001
}
截至2022年2月3日,GNU C库已更新至2.35版。因此,现在支持%b以二进制格式输出。
的输出现在支持%b格式的printf系列函数 二进制整数,如ISO C2X草案中指定的,以及%B变体 采用ISO C2X草案建议的格式。
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);
}
}
应该工作-未经测试。