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) {
                printf("0b0");
                return;
        }   

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

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

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

Source code on GitHub (with driver program).

Update

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
-0b1000000000000000000000000000000000000000000000000000000000000000

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s