Search code examples
c++cfloating-pointfloating-point-conversion

Converting 4 raw bytes into 32-bit floating point


I'm trying to re-construct a 32-bit floating point value from an eeprom.

The 4 bytes in eeprom memory (0-4) are : B4 A2 91 4D

and the PC (VS Studio) reconstructs it correctly as 3.054199 * 10^8 (the floating point value I know should be there)

Now I'm moving this eeprom to be read from an 8-bit Arduino, so not sure if it's compiler/platform thing, but when I try reading the 4 bytes into a 32-bit dword, and then typecast it to a float, the value I get isn't even close.

Assuming the conversion can't be done automatically with the standard ansi-c compiler, how can the 4 bytes be manually parsed to be a float?


Solution

  • The safest way, and due to compiler optimization also as fast as any other, is to use memcpy:

    uint32_t dword = 0x4D91A2B4;
    float f;
    memcpy(&f, &dw, 4);
    

    Demo: http://ideone.com/riDfFw