我可以用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"
当前回答
我的解决方案返回一个int,然后可以在printf中使用。它还可以以大端序或小端序返回位。
#include <stdio.h>
#include <stdint.h>
int binary(uint8_t i,int bigEndian)
{
int j=0,m = bigEndian ? 1 : 10000000;
while (i)
{
j+=m*(i%2);
if (bigEndian) m*=10; else m/=10;
i >>= 1;
}
return j;
}
int main()
{
char buf[]="ABCDEF";
printf("\nbig endian = ");
for (int i=0; i<5; i++) printf("%08d ",binary(buf[i],1));
printf("\nwee endian = ");
for (int i=0; i<5; i++) printf("%08d ",binary(buf[i],0));
getchar();
return 0;
}
输出
big endian = 01000001 01000010 01000011 01000100 01000101 01000110
wee endian = 10000010 01000010 11000010 00100010 10100010 01100010
其他回答
我喜欢的代码由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;
}
没有标准和便携的方式。
有些实现提供了itoa(),但大多数实现中都没有,而且它的接口有些糟糕。但是代码在链接后面,应该可以让您非常容易地实现自己的格式化程序。
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中的大多数操作呈现给一个或很少几个机器指令。
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
printf("Welcome\n\n\n");
unsigned char x='A';
char ch_array[8];
for(int i=0; x!=0; i++)
{
ch_array[i] = x & 1;
x = x >>1;
}
for(--i; i>=0; i--)
printf("%d", ch_array[i]);
getch();
}
打印最低有效位并向右移出。这样做直到整数变为零,打印的二进制表示没有前导零,但顺序相反。使用递归,可以很容易地纠正顺序。
#include <stdio.h>
void print_binary(unsigned int number)
{
if (number >> 1) {
print_binary(number >> 1);
}
putc((number & 1) ? '1' : '0', stdout);
}
对我来说,这是最干净的解决方案之一。如果您喜欢0b前缀和一个尾随的新行字符,我建议对函数进行包装。
在线演示