C Puzzle #8


This is a very small program as you can see. Whst it will do is: It will just count the number of bits set in a given number.

Input is this  
Output is this
0
0(0000000)
5
2(0000101)
7
3(0000111)
int Count_Bits (unsigned int x )
  {
      static unsigned int mask[] = { 0x55555555,
          0x33333333,
          0x0F0F0F0F,
          0x00FF00FF,
          0x0000FFFF
          } ;

          int i ;
          int shift ; /* Number of positions to shift to right*/
          for ( i =0, shift =1; i < 5; i ++, shift *= 2)
                  x = (x & mask[i ])+ ( ( x >> shift) & mask[i]);
          return x;
  }
Can you find out the logic used here?
Its really difficult na!!

No comments:

Post a Comment

Your answer for the question

Related Posts Plugin for WordPress, Blogger...