title: Number of bits set in a number
body: <p>The following the magical formula which gives the number of bits set in a number (Hamming weight).</p>
  
  <pre><code>/*Code to Calculate count of set bits in a number*/
  int c;
  int v = 7;
  v = v - ((v &gt;&gt; 1) &amp; 0x55555555);                    // reuse input as temporary
  v = (v &amp; 0x33333333) + ((v &gt;&gt; 2) &amp; 0x33333333);     // temp
  c = ((v + (v &gt;&gt; 4) &amp; 0xF0F0F0F) * 0x1010101) &gt;&gt; 24; // count
  printf(" Number of Bits is %d",c);
  /*-----------------------------------*/
  </code></pre>
  
  <p>from:
  <a href="http://graphics.stanford.edu/~seander/bithacks.html" rel="noreferrer">http://graphics.stanford.edu/~seander/bithacks.html</a></p>
  
  <p>Can anyone please explain me the rationale behind this?</p>