How can I convert 4 bytes storing an IEEE 754 floating point number to a float value in C?

前端 未结 3 1044
生来不讨喜
生来不讨喜 2020-12-18 11:14

My program reads into 4 bytes an IEEE 754 floating point number from a file. I need to portable convert those bytes to my C compilers float type. In other words I need a fun

3条回答
  •  一向
    一向 (楼主)
    2020-12-18 11:55

    If your implementation can guarantee correct endianness:

    float raw2ieee(uint8_t *raw)
    {
        // either
        union {
            uint8_t bytes[4];
            float fp;
        } un;
        memcpy(un.bytes, raw, 4);
        return un.fp;
    
        // or, as seen in the fast inverse square root:
        return *(float *)raw;
    }
    

提交回复
热议问题