binary printf()

hacker_compA friend of mine pointed out the lack of binary representation output in printf() during a discussion. It is a reasonable requirement, given the fact printf() supports hex and octal representations.

A solution is available on StackOverflow, which unfortunately, calls printf() 64 times for a 64 bit value with all bits used. It also runs into an infinite loop for negative values.

Here’s a much faster implementation that works for signed (positive or negative) 64 bit values (if you need beyond that, feel free to extend it). Keep in mind to account for the MSB sign bit.

void printbin(long long val)
        int count = 63; 
        char binstr[65] = {0};

        if (!val) {

        /* If negative, get the 2's complement */
        if (val < 0) {
                val = ~val + 1;
         } else

         while (val && count >= 0) {
                binstr[count--] = "01"[val & 1]; 
                val >>= 1;

        printf("%s", binstr + count);

Source code on GitHub (with driver program).


I modified the code to remove the OVERFLOW warning. The supported values are defined by the function argument (signed 64-bit). Sample output (with driver function) for -263 or 0x8000000000000000 (this number is the 2’s complement of itself):

$ ./binprint -9223372036854775808

Leave a Reply

Your email address will not be published. Required fields are marked *