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

标签 c floating-point ieee-754

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

最佳答案

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

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;
}

关于c - 如何将存储 IEEE 754 float 的 4 个字节转换为 C 中的浮点值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12242187/

相关文章:

c - 如何将数据从UDP Server 发送到NAT 后面的UDP client?

c - 将输入视为十六进制值

c - strcmp 不给 0,但两个参数相同

c++ - 单精度不是 6 位数字保证吗?

c++ - 这个输入中的 float 和 double 有什么区别?

c++ - 与正零 (+0.0) 相比,负零 (-0.0) 的行为

javascript - JSPack 无法将 double 转换为字节

访问预定义数组时代码崩溃

go - 使用相同浮点常量值的不同模式会导致不同的结果

在不损失精度的情况下将 unsigned 转换为 double 到 unsigned