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"
I liked the code by paniq, the static buffer is a good idea. However it fails if you want multiple binary formats in a single printf() because it always returns the same pointer and overwrites the array.
Here's a C style drop-in that rotates pointer on a split buffer.
Based on @ideasman42's suggestion in his answer, this is a macro that provides
int8
,16
,32
&64
versions, reusing theINT8
macro to avoid repetition.This outputs:
For readability you can change :
#define PRINTF_BINARY_SEPARATOR
to#define PRINTF_BINARY_SEPARATOR ","
or#define PRINTF_BINARY_SEPARATOR " "
This will output:
or
Next will show to you memory layout:
This code should handle your needs up to 64 bits. I created 2 functions pBin & pBinFill. Both do the same thing, but pBinFill fills in the leading spaces with the fillChar. The test function generates some test data, then prints it out using the function.
The
printf()
family is only able to print in base 8, 10, and 16 using the standard specifiers directly. I suggest creating a function that converts the number to a string per code's particular needs.To print in any base [2-36]
All other answers so far have at least one of these limitations.
Use static memory for the return buffer. This limits the number of times the function may be used as an argument to
printf()
.Allocate memory requiring the calling code to free pointers.
Require the calling code to explicitly provide a suitable buffer.
Call
printf()
directly. This obliges a new function for tofprintf()
,sprintf()
,vsprintf()
, etc.Use a reduced integer range.
The following has none of the above limitation. It does require C99 or later and use of
"%s"
. It uses a compound literal to provide the buffer space. It has no trouble with multiple calls in aprintf()
.Output
Here's how I did it for an unsigned int