title: Cast Integer to Float using Bit Manipulation breaks on some integers in C
body: <p>Working on a class assignment, I'm trying to cast an integer to a float only using bit manipulations (limited to any integer/unsigned operations incl. ||, &amp;&amp;. also if, while).  My code is working for most values, but some values are not generating the results I'm looking for.</p>
  
  <p>For example, if x is 0x807fffff, I get 0xceff0001, but the correct result should be 0xceff0000.  I think I'm missing something with my mantissa and rounding, but can't quite pin it down.  I've looked at some other threads on SO as well <a href="https://stackoverflow.com/questions/20302904/converting-int-to-float-float-to-int-using-bitwise/20308114#20308114">converting-int-to-float</a> and <a href="https://stackoverflow.com/questions/12336314/how-to-manually-bitwise-perform-floatx">how-to-manually</a></p>
  
  <pre><code>unsigned dl22(int x) {
  
  
      int tmin = 0x1 &lt;&lt; 31;
      int tmax = ~tmin;
  
      unsigned signBit = 0;
      unsigned exponent;
      unsigned mantissa;
      int bias = 127;
  
      if (x == 0) {
          return 0;
      }
  
      if (x == tmin) {
          return 0xcf &lt;&lt; 24;
      }
  
      if (x &lt; 0) {
          signBit = x &amp; tmin;
          x = (~x + 1);
      }
  
  
      exponent = bias + 31;
  
      while ( ( x &amp; tmin) == 0 ) {
          exponent--;
          x &lt;&lt;= 1;
      }
  
      exponent &lt;&lt;= 23;
      int mantissaMask = ~(tmin &gt;&gt; 8);
      mantissa = (x &gt;&gt; 8) &amp; mantissaMask;
  
      return (signBit | exponent | mantissa);
  }
  </code></pre>
  
  <p><strong>EDIT/UPDATE</strong>
  Found a viable solution - see below</p>