title: How to convert an unsigned int to a float?
body: <p>I need to build a function that returns the bit-level equivalent of (float)x without using any floating data types, operations or constants.  I think I have it, but when I run the test file, it returns that there's an infinite loop.  Any debugging help would be appreciated.</p>
  
  <p>I'm allowed to use any integer/unsigned operations including ||, &amp;&amp;, if, while.
  Also, I can only use 30 operations</p>
  
  <pre><code>unsigned float_i2f(int x) {
      printf("\n%i", x);
      if (!x) {return x;}
      int mask1 = (x &gt;&gt; 31);
      int mask2 = (1 &lt;&lt; 31);
      int sign = x &amp; mask2;
      int complement = ~x + 1;
      //int abs = (~mask1 &amp; x) + (mask1 &amp; complement);
      int abs = x;
      int i = 0, temp = 0;
      while (!(temp &amp; mask2)){
          temp = (abs &lt;&lt;i);
          i = i + 1;
      }
      int E = 32 - i;
      int exp = 127 + E;
      abs = abs &amp; (-1 ^ (1 &lt;&lt; E));
      int frac;
      if ((23 - E)&gt;0)
          frac = (abs &lt;&lt; (23 - E));
      else
          frac = (abs &gt;&gt; (E - 23));
      int rep = sign + (exp &lt;&lt; 23) + frac;
      return rep;
  }
  </code></pre>
  
  <p>In response to the very helpful comments and answers, here is the updated code, now only failing for 0x80000000:</p>
  
  <pre><code>unsigned float_i2f(int x) {
      int sign;
      int absX;
      int E = -1;
      int shift;
      int exp;
      int frac;
      // zero is the same in int and float:
      if (!x) {return x;}
  
      // sign is bit 31: that bit should just be transferred to the float:
      sign = x &amp; 0x80000000;
  
      // if number is &lt; 0, take two's complement:
      if (sign != 0) {
          absX = ~x + 1;
      }
      else
          absX = x;
  
      shift = absX;
      while ((!!shift) &amp;&amp; (shift != -1)) {
          //std::cout &lt;&lt; std::bitset&lt;32&gt;(shift) &lt;&lt; "\n";
          E++;
          shift = (shift &gt;&gt; 1);
      }
      if (E == 30) { E++;}
      exp = E + 127+24;
      exp = (exp &lt;&lt; 23);
      frac = (absX &lt;&lt; (23 - E)) &amp; 0x007FFFFF;
      return sign + exp + frac;
  }
  </code></pre>
  
  <p>Anyone have any idea where the bug is in the revised code?  Thank you all again!</p>