====== How to print binary to stdout in C ======
In standard C, there is no format specifier (such as %d, %x, etc..) to printf that allows printing binary representation of data.
===== Example for printing binary data =====
This code snippet shows how to print binary representation of bytes in C.
#include
#include
void
print_byte(uint8_t byte)
{
uint8_t i;
for (i = 0; i < 8; i++)
if (byte & (1 << i))
printf("1");
else
printf("0");
}
int
main()
{
print_byte(4);
return 0;
}
Compile and run to see the binary representation of the integer 4 printed in binary.
$cc test.c
$./a.out
00100000
If you need to display a whole string in binary, simply use the function print_byte for all characters of the string.
===== More coding articles =====
{{topic>coding&noheader}}
{{tag>coding howto}}