Tuesday, November 8, 2011

Print Bits

I was handling a bitmap some time ago, and I came into the need to see what was the actual bit representation of the numbers I was using. So I wrote this function:

void print_bits(int number) {
        unsigned long mask = 0b10000000000000000000000000000000 ;
        char digit;

        while(mask) {
                digit = ((mask & number) ? '1' : '0');
                mask >>= 1;

This function accepts an integer, and prints on screen it's actual binary representation. Basically it takes a mask whit only the most significant bit set, bitwise ands it with the number and prints either 0 or 1 depending on that bit's value. Then it shifts the mask one position right and iterates, until all the bits are shown.

The 'b' in the mask is a GNU extension, which tells that the number is represented directly in binary. If you are not using gcc, or don't like that series of 0's, simply replace it with the hex counterpart: 0x80000000.

This works both in 32 and 64 bits on Intel x86, as integers there are both 32 bit wide. If you want to deal with a larger number representation, either change the initial mask, or set it to 0x1 and change the shift from >> to <<.

You can use this code to see how numbers are represented. With some minor changes, you can use it to show any representation, be that a float or a more complex struct, for example by dereferencing a pointer.

No comments:

Post a Comment