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"
Here is a small variation of paniq's solution that uses templates to allow printing of 32 and 64 bit integers:
And can be used like:
Here is the result:
Here's a version of the function that does not suffer from reentrancy issues or limits on the size/type of the argument:
Note that this code would work just as well for any base between 2 and 10 if you just replace the 2's by the desired base. Usage is:
Where
x
is any integral expression.My solution:
Maybe a bit OT, but if you need this only for debuging to understand or retrace some binary operations you are doing, you might take a look on wcalc (a simple console calculator). With the -b options you get binary output.
e.g.
There is no formatting function in the C standard library to output binary like that. All the format operations the printf family supports are towards human readable text.
should work - untested.