Bits, Part 1

Dave Sinkula 0 Tallied Votes 370 Views Share

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
*/
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.