我可以用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 <stdio.h> /* printf */
#include <string.h> /* strcat */
#include <stdlib.h> /* strtol */
const char *byte_to_binary
(
int x
)
{
static char b[9];
b[0] = '\0';
int z;
for (z = 128; z > 0; z >>= 1)
{
strcat(b, ((x & z) == z) ? "1" : "0");
}
return b;
}
int main
(
void
)
{
{
/* binary string to int */
char *tmp;
char *b = "0101";
printf("%d\n", strtol(b, &tmp, 2));
}
{
/* byte to binary string */
printf("%s\n", byte_to_binary(5));
}
return 0;
}
其他回答
void PrintBinary( int Value, int Places, char* TargetString)
{
int Mask;
Mask = 1 << Places;
while( Places--) {
Mask >>= 1; /* Preshift, because we did one too many above */
*TargetString++ = (Value & Mask)?'1':'0';
}
*TargetString = 0; /* Null terminator for C string */
}
调用函数“拥有”字符串…:
char BinaryString[17];
...
PrintBinary( Value, 16, BinaryString);
printf( "yadda yadda %s yadda...\n", BinaryString);
取决于您的CPU, PrintBinary中的大多数操作呈现给一个或很少几个机器指令。
C标准库中没有这样输出二进制的格式化函数。printf家族支持的所有格式操作都是针对人类可读的文本。
但对我来说很管用:
#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
#define BYTE_TO_BINARY(byte) \
(byte & 0x80 ? '1' : '0'), \
(byte & 0x40 ? '1' : '0'), \
(byte & 0x20 ? '1' : '0'), \
(byte & 0x10 ? '1' : '0'), \
(byte & 0x08 ? '1' : '0'), \
(byte & 0x04 ? '1' : '0'), \
(byte & 0x02 ? '1' : '0'), \
(byte & 0x01 ? '1' : '0')
printf("Leading text "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte));
对于多字节类型
printf("m: "BYTE_TO_BINARY_PATTERN" "BYTE_TO_BINARY_PATTERN"\n",
BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m));
不幸的是,你需要所有额外的引号。这种方法存在宏的效率风险(不要将函数作为参数传递给BYTE_TO_BINARY),但避免了这里的其他一些建议中的内存问题和多次调用strcat。
一些运行时支持“%b”,尽管这不是标准。
也可以在这里看到一个有趣的讨论:
http://bytes.com/forum/thread591027.html
HTH
截至2022年2月3日,GNU C库已更新至2.35版。因此,现在支持%b以二进制格式输出。
的输出现在支持%b格式的printf系列函数 二进制整数,如ISO C2X草案中指定的,以及%B变体 采用ISO C2X草案建议的格式。