Search code examples
floating-pointieee-754

How is 1 encoded in C/C++ as a float (assuming IEEE 754 single precision representation)?


My impression is that C float has 8 bits of exponent and 23 bits of mantissa.

So one is 0011 1111 1000 0000 0000 0000 0000 0000 = 0x3F800000.

However, the following code produced 1.06535e+09 instead of 1. Can anyone help me understand why?

#include <iostream>
#include <math.h>  

using namespace std;

int main()
{
    float i = 0x3F800000;
    cout<<i << endl;
    return 0;
}

Solution

  • How is 1 coded in C as a float?

    Can anyone help me understand why (code fails)?

    float i = 0x3F800000;
    

    is the same as i = 1065353216;


    In C, to overlay the bit pattern use a union or use memcpy().

    In C++, suggest memcpy().

    Using a cast risks failure due to anti-aliasing. @Eric Postpischil

    #include <stdio.h>
    #include <stdint.h>
    
    _Static_assert(sizeof(float) == sizeof(uint32_t), "Unexpected types");
    
    int main(void) {
      union {
        uint32_t u; 
        float f;
      } x = {.u = 0x3f800000};
      float f = x.f;
      printf("%e\n", f);
      return 0;
    }
    

    On less common systems, this can fail due to

    • float is not binary32.

    • Endian differs between float/uint32