title: Finding the exponent of n = 2**x using bitwise operations [logarithm in base 2 of n]
body: <p>Is there a straightforward way to extracting the exponent from a power of 2 using bitwise operations only?</p>
  
  <p><strong>EDIT:</strong> Although the question was originally about bitwise operations, the thread is a good read also if you are wondering <strong>"What's the fastest way to find X given Y = 2</strong>X <em>in Python</em>?"**</p>
  
  <p>I am currently trying to optimize a routine (<a href="http://en.wikipedia.org/wiki/Rabin-Miller_primality_test" rel="nofollow noreferrer">Rabin-Miller primality test</a>) that reduces an <strong>even number</strong> N in the forms <strong><code>2**s * d</code></strong>. I can get the <strong><code>2**s</code></strong> part by:</p>
  
  <pre><code>two_power_s = N &amp; -N
  </code></pre>
  
  <p>but I can't find a way to extract just "<strong>s</strong>" with a bitwise operation. Workarounds I am currently testing without too much satisfaction (they are all pretty much slow) are:</p>
  
  <ul>
  <li>using the logarithm function</li>
  <li>manipulating the binary representation of 2**s (i.e. counting the trailing zeroes)</li>
  <li>looping on a division by 2 until the result is 1</li>
  </ul>
  
  <p>I am using python, but the answer to this question should be language agnostic, I suppose.</p>