我可以用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"
当前回答
还有一种想法是将数字转换为十六进制格式,然后将每个十六进制密码解码为四个“位”(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
其他回答
下面的函数返回给定无符号整数的二进制表示形式,使用不带前导零的指针算术:
const char* toBinaryString(unsigned long num)
{
static char buffer[CHAR_BIT*sizeof(num)+1];
char* pBuffer = &buffer[sizeof(buffer)-1];
do *--pBuffer = '0' + (num & 1);
while (num >>= 1);
return pBuffer;
}
注意,不需要显式设置NUL结束符,因为buffer表示一个具有静态存储持续时间的对象,该对象已经被全0填充。
通过简单地修改num形式参数的类型,可以很容易地将其适应为无符号long long(或另一个无符号整数)。
CHAR_BIT要求包含<limits.h>。
下面是一个用法示例:
int main(void)
{
printf(">>>%20s<<<\n", toBinaryString(1));
printf(">>>%-20s<<<\n", toBinaryString(254));
return 0;
}
其期望输出为:
>>> 1<<<
>>>11111110 <<<
也许有人会发现这个解决方案很有用:
void print_binary(int number, int num_digits) {
int digit;
for(digit = num_digits - 1; digit >= 0; digit--) {
printf("%c", number & (1 << digit) ? '1' : '0');
}
}
C标准库中没有这样输出二进制的格式化函数。printf家族支持的所有格式操作都是针对人类可读的文本。
const char* byte_to_binary(int x)
{
static char b[sizeof(int)*8+1] = {0};
int y;
long long z;
for (z = 1LL<<sizeof(int)*8-1, y = 0; z > 0; z >>= 1, y++) {
b[y] = (((x & z) == z) ? '1' : '0');
}
b[y] = 0;
return b;
}
你可以使用一个小表格来提高速度。类似的技术在嵌入式世界中也很有用,例如,反转一个字节:
const char *bit_rep[16] = {
[ 0] = "0000", [ 1] = "0001", [ 2] = "0010", [ 3] = "0011",
[ 4] = "0100", [ 5] = "0101", [ 6] = "0110", [ 7] = "0111",
[ 8] = "1000", [ 9] = "1001", [10] = "1010", [11] = "1011",
[12] = "1100", [13] = "1101", [14] = "1110", [15] = "1111",
};
void print_byte(uint8_t byte)
{
printf("%s%s", bit_rep[byte >> 4], bit_rep[byte & 0x0F]);
}
1我主要指的是嵌入式应用程序,其中优化器不是那么激进,速度差异是可见的。