title: How does this code work to count number of 1-bits?
body: <p>I found the following code to count the number of <code>1-bits</code> in binary representation for given integer. Can anyone explain how it works? And how are the bit masks chosen for such task? Thanks.</p>
  
  <pre><code>int count_one(int x)
  {
      x = (x &amp; (0x55555555)) + ((x &gt;&gt; 1) &amp; (0x55555555));
      x = (x &amp; (0x33333333)) + ((x &gt;&gt; 2) &amp; (0x33333333));
      x = (x &amp; (0x0f0f0f0f)) + ((x &gt;&gt; 4) &amp; (0x0f0f0f0f));
      x = (x &amp; (0x00ff00ff)) + ((x &gt;&gt; 8) &amp; (0x00ff00ff));
      x = (x &amp; (0x0000ffff)) + ((x &gt;&gt; 16) &amp; (0x0000ffff));
      return x;
  }
  </code></pre>