title: Bitwise operations to produce power of two in Python
body: <p>In just intonation theory, a type of music theory, intervals between notes are expressed with rational numbers. Doubling a frequency with a 2:1 ratio brings it up an octave and a 1:1 ratio is no change; a unison. So if I have an interval <em>n</em> that is larger than an octave or smaller than a unison (it goes down), it is useful to 'justify' it. That is, to make 1 ≤ <em>n</em> ≤ 2. I've been doing this in Python with the following function:</p>
  
  <pre><code>def justify(n):
      return n / 2 ** floor( log(n,2) )
  </code></pre>
  
  <p>The actual function involves the fractions library, but this gets the job done with floats and ints. The log finds to what power of 2 <em>n</em> is and floor rounds it down so that the resulting divisor is the nearest power of 2 below <em>n</em>. I've also tried this:</p>
  
  <pre><code>def justify(n):
      return n / int( '1'.ljust( len( bin(n) ) - 2, '0' ), 2 )
  </code></pre>
  
  <p>This one just take the length of the binary representation and pads zeroes based on that. Of course, that only works with ints. I was wondering if there is any way to perform this operation with bitwise operations. It seems like the binary would lend itself well to the power of 2 operation. At minimum, I would like to see a way to replace <code>2 ** floor( log(n,2) )</code> with something bitwise. Extra points if it can handle floats, but I understand that's more complicated.</p>