title: How to move all set bits to the right?
body: <p>Question: How to develop algorithm to shift all set bits (<code>1</code>) in <strong>32-bits integer</strong> to the right</p>
  
  <p>Example </p>
  
  <pre><code>V= 0b01001000110010 
  </code></pre>
  
  <p>The <code>V</code> contains 5 set bits and if we shift them to the right we get:</p>
  
  <pre><code>V = 0b011111
  </code></pre>
  
  <p>What I have tried:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>The above code return the number of set bits in 32-bits integer</p>
  
  <p>and with the following code</p>
  
  <pre><code>c = (1&lt;&lt;c) - 1;
  </code></pre>
  
  <p>we will get the <code>c</code> first bits set to <code>1</code>. <a href="https://stackoverflow.com/questions/15816927/bit-manipulation-clearing-range-of-bits/15817020#15817020">Explaination</a></p>
  
  <p>Are there other algorithmes better than the above solution?</p>
  
  <p>Is it possible to use only bitwise operations (<code>&amp;</code>,<code>|</code>, <code>^</code>, <code>~</code>, <code>&gt;&gt;</code>, <code>&lt;&lt;</code>) in the proposed solutions?</p>