title: c++ bit shifting a float
body: <pre><code>float length =  32.32f;
  long  i = *(long*)&amp;length ; // casting a float pointer to a long pointer...
  i &gt;&gt;= 1; // right shift i but 1 ... or div by 2
  length = *(float*)&amp;i; // is this necessary?
  </code></pre>
  
  <p>Printing length gives: 0.0</p>
  
  <p>The end result should be: 16.16;</p>
  
  <p>This idea is from <a href="http://en.wikipedia.org/wiki/Fast_inverse_square_root" rel="noreferrer">http://en.wikipedia.org/wiki/Fast_inverse_square_root</a>. Im trying to understand the section of the code were the long in a float is taken out and bitwise operations are performed on it. Im guessing the point is to improve performance by avoiding branching? </p>
  
  <p>The above code fails. Can anyone tell me what im doing wrong? I was under the impression that it was as simple as getting the <code>long</code> storage in a <code>float</code> and manipulation it, is this wrong?    </p>
  
  <p>i found something interesting, if i change the code to:</p>
  
  <pre><code> float length =  32.32f;
   long  i = *(long*)&amp;length ;
   i  = 0x5f3759df - ( i &gt;&gt; 1 ); 
   length = *(float*)&amp;i;
  </code></pre>
  
  <p>adding this number (0x5f3759df) to the mix.</p>
  
  <p>Printing out length*100 gives : 17.0538 // approximation of 16.16<br>
  trying it with different length gives the same results. </p>
  
  <p>eg: length = 100; result is : 10.3299?? // almost... </p>