title: clear all but the two most significant set bits in a word
body: <p>Given an 32 bit int which is known to have at least 2 bits set, is there a way to efficiently clear all except the 2 most significant set bits?  i.e. I want to ensure the output has exactly 2 bits set.</p>
  
  <p>What if the input is guaranteed to have only 2 or 3 bits set.?</p>
  
  <p>Examples:</p>
  
  <pre><code>0x2040 -&gt; 0x2040
  0x0300 -&gt; 0x0300
  0x0109 -&gt; 0x0108
  0x5040 -&gt; 0x5000
  </code></pre>
  
  <hr>
  
  <p><strong>Benchmarking Results:</strong></p>
  
  <p>Code:</p>
  
  <pre><code>QueryPerformanceFrequency(&amp;freq);
  /***********/
  value = (base =2)|1;
  QueryPerformanceCounter(&amp;start);
  for (l=0;l&lt;A_LOT; l++)
  {
    //!!value calculation goes here
    junk+=value;    //use result to prevent optimizer removing it.
  
    //advance to the next 2|3 bit word
    if (value&amp;0x80000000)
    {  if (base&amp;0x80000000)
       {  base=6;
       }
       base*=2;
       value=base|1;
    }
    else
    {  value&lt;&lt;=1;
    }
  }
  QueryPerformanceCounter(&amp;end);
  time = (end.QuadPart - start.QuadPart);
  time /= freq.QuadPart;
  printf("--------- name\n");
  printf("%ld loops took %f sec (%f additional)\n",A_LOT, time, time-baseline);
  printf("words /sec = %f Million\n",A_LOT/(time-baseline)/1.0e6); 
  </code></pre>
  
  <p>Results on using VS2005 default release settings on Core2Duo E7500@2.93 GHz:</p>
  
  <pre><code>--------- BASELINE
  1000000 loops took 0.001630 sec
  --------- sirgedas
  1000000 loops took 0.002479 sec (0.000849 additional)
  words /sec = 1178.074206 Million
  --------- ashelly
  1000000 loops took 0.004640 sec (0.003010 additional)
  words /sec = 332.230369 Million
  --------- mvds
  1000000 loops took 0.005250 sec (0.003620 additional)
  words /sec = 276.242030 Million
  --------- spender
  1000000 loops took 0.009594 sec (0.007964 additional)
  words /sec = 125.566361 Million
  --------- schnaader
  1000000 loops took 0.025680 sec (0.024050 additional)
  words /sec = 41.580158 Million
  </code></pre>