如何将存储IEEE 754浮点数的4个字节转换为C中的浮点值?

Ste*_*lus 2 c floating-point ieee-754

我的程序从文件中读取4个字节的IEEE 754浮点数.我需要将这些字节可移植地转换为我的C编译器浮点类型.换句话说,我需要一个函数与float IEEE_754_to_float(uint8_t raw_value[4])我的C程序的原型.

小智 5

如果您的实现可以保证正确的字节顺序:

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;
}
Run Code Online (Sandbox Code Playgroud)