Is there a printf converter to print in binary format?
I can print with printf as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?
I am running gcc.
printf("%d %x %on", 10, 10, 10); //prints "10 A 12n"
print("%bn", 10); // prints "%bn"
Hacky but works for me:
#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));
For multi-byte types
printf("m: "BYTE_TO_BINARY_PATTERN" "BYTE_TO_BINARY_PATTERN"n",
BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m));
You need all the extra quotes unfortunately. This approach has the efficiency risks of macros (don't pass a function as the argument to BYTE_TO_BINARY
) but avoids the memory issues and multiple invocations of strcat in some of the other proposals here.
Print Binary for Any Datatype
//assumes little endian
void printBits(size_t const size, void const * const ptr)
{
unsigned char *b = (unsigned char*) ptr;
unsigned char byte;
int i, j;
for (i=size-1;i>=0;i--)
{
for (j=7;j>=0;j--)
{
byte = (b[i] >> j) & 1;
printf("%u", byte);
}
}
puts("");
}
test
int main(int argv, char* argc[])
{
int i = 23;
uint ui = UINT_MAX;
float f = 23.45f;
printBits(sizeof(i), &i);
printBits(sizeof(ui), &ui);
printBits(sizeof(f), &f);
return 0;
}
这里是一个简单的黑客来演示技术来做你想做的事情。
#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] = ' ';
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("%dn", strtol(b, &tmp, 2));
}
{
/* byte to binary string */
printf("%sn", byte_to_binary(5));
}
return 0;
}
链接地址: http://www.djcxy.com/p/72212.html
上一篇: 如何在C中打印int的大小?