Search code examples
cfloating-pointbit-manipulationfloating-point-conversion

Bitwise Float To Int


I am trying to figure out the algorithm to this but all I get with google is doing it with casting. I need to know the details.

So if we have a float x and want to return its binary representation what do we need to do?

I know we need to return the float if its NaN or a infinity but otherwise what are the steps?

EDIT

The function takes in an unsigned int, to be used as if it was a float, and then return the integer the number represents. I cannot use casting, just conditionals and bit-wise operators.


Solution

  • Alternatively, use a union:

    typedef union 
    {
        float f_;
        int   i_;
    } FloatBits;
    
    FloatBits fb;
    
    fb.f_ = 1.5;
    

    Then fb.i_ contains the float mapped onto an int to allow extraction of the bits. Again, usual assunptions about the size of types - you can verify these using sizeof.

    Using this approach, you can play with setting the bits in fb.i_ directly and seeing them mapped back into the float.