Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Is there a printf converter to print in binary format?

I can print with printf as a hex or octal number. Is there an organization tag to print as binary, or arbitrary base?

I'm running gcc.
*printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
print("%b\n", 10); // prints "%b\n"
by

5 Answers

rahul07
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;
}
RoliMishra
You could use a small table to improve your speed. Similar techniques are useful in the embedded world, for example, to invert a byte:

const char *bit_rep[16] = {
[ 0] = "0000", [ 1] = "0001", [ 2] = "0010", [ 3] = "0011",
[ 4] = "0100", [ 5] = "0101", [ 6] = "0110", [ 7] = "0111",
[ 8] = "1000", [ 9] = "1001", [10] = "1010", [11] = "1011",
[12] = "1100", [13] = "1101", [14] = "1110", [15] = "1111",
};

void print_byte(uint8_t byte)
{
printf("%s%s", bit_rep[byte >> 4], bit_rep[byte & 0x0F]);
}
akshay1995
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.

#include <stdio.h>

void print_binary(unsigned int number)
{
if (number >> 1) {
print_binary(number >> 1);
}
putc((number & 1) ? '1' : '0', stdout);
}

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.
kshitijrana14
Here is a quick hack to demonstrate techniques to do what you want.
#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] = '\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("%d\n", strtol(b, &tmp, 2));
}

{
/* byte to binary string
/

printf("%s\n", byte_to_binary(5));
}

return 0;
}
sandhya6gczb
Here is a small program to convert decimal to 16-bit binary numbers.

#include <stdio.h>
int main()
{
int n, i, a;

printf("Enter an integer (decimal number)");
scanf("%d", &n);

printf("%d in binary number system is:\n", n);
//for example we are going to represent it with 16 bits
for (i = 15; i >= 0; i--)
{
a = n >> i;

if (a & 1)
printf("1");
else
printf("0");
}

printf("\n");

return 0;
}

Login / Signup to Answer the Question.