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 %o\n", 10, 10, 10); //prints "10 A 12\n"
print("%b\n", 10); // prints "%b\n"
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 %o\n", 10, 10, 10); //prints "10 A 12\n"
print("%b\n", 10); // prints "%b\n"
A small utility function in C to do this while solving a bit manipulation problem. This goes over the string checking each set bit using a mask (1<
No standard and portable way.
Some implementations provide itoa(), but it's not going to be in most, and it has a somewhat crummy interface. But the code is behind the link and should let you implement your own formatter pretty easily.
Here is a quick hack to demonstrate techniques to do what you want.
Print bits from any type using less code and resources
This approach has as attributes:
Output
I have used another approach (bitprint.h) to fill a table with all bytes (as bit strings) and print them based on the input/index byte. It's worth taking a look.
Based on @William Whyte's answer, this is a macro that provides
int8
,16
,32
&64
versions, reusing theINT8
macro to avoid repetition.This outputs:
For readability you may want to add a separator for eg:
Print the least significant bit and shift it out on the right. Doing this until the integer becomes zero prints the binary representation without leading zeros but in reversed order. Using recursion, the order can be corrected quite easily.
To me, this is one of the cleanest solutions to the problem. If you like
0b
prefix and a trailing new line character, I suggest wrapping the function.Online demo