Start New Discussion within our Software Development Community

It is often instructive to display the bits of a value. (This is similar to 'converting' an integer to binary.) The way I have done this in this snippet is to start at the most significant bit and work your way through all the rest of the bits. (Continued in Part 2.)

#include <stdio.h>

void bits_uint(unsigned int value)
{
   unsigned int bit;
   for ( bit = /* msb */(~0U >> 1) + 1; bit > 0; bit >>= 1 )
   {
      putchar(value & bit ? '1' : '0');
   }
   putchar('\n');
}

int main(void)
{
   unsigned int u;
   /*
    * Using this code to explain itself a little -or- what is '(~0U >> 1) + 1'?
    * Short answer: this expression sets only the most significant bit (MSB)
    *               of an unsigned integer.
    */
   u =   0U          ; printf("  0U           : "); bits_uint(u);
   u =  ~0U          ; printf(" ~0U           : "); bits_uint(u);
   u =  ~0U >> 1     ; printf(" ~0U >> 1      : "); bits_uint(u);
   u = (~0U >> 1) + 1; printf("(~0U >> 1) + 1 : "); bits_uint(u);
   return 0;
}

/* my output (spaces edited for display here)
0U             : 00000000000000000000000000000000
~0U            : 11111111111111111111111111111111
~0U >> 1       : 01111111111111111111111111111111
(~0U >> 1) + 1 : 10000000000000000000000000000000
*/
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.