c++ - 将字节数组转换为 float

标签 c++ c casting

我有一个程序需要接收 4 个字节并将它们转换为 IEEE-754 float 。字节被乱序传输,但我可以把它们按顺序放回去就好了。我的问题是将它们转换为 float 。代码的相关部分:

//Union to store bytes and float on top of each other
typedef union {
    unsigned char b[4];
    float f;
} bfloat;

//Create instance of the union
bfloat Temperature;

//Add float data using transmitted bytes
MMI.Temperature.b[2] = 0xD1;//MMIResponseMsg[7];
MMI.Temperature.b[3] = 0xE1;//MMIResponseMsg[8];
MMI.Temperature.b[0] = 0x41;//MMIResponseMsg[9];
MMI.Temperature.b[1] = 0xD7;//MMIResponseMsg[10];

//Attempting to read the float value
lWhole=(long) ((float)MMI.Temperature.f);
//DEBUGGING
stevenFloat = (float)MMI.Temperature.f;

lWhole 是一个 long 而 stevenFloat 是一个 float。调试时我可以看到我分配给字节数组的值被正确存储,但是 stevenFloatlWhole 的值不正确。它们似乎徘徊在接近 0 或接近最大浮点/长值的位置。对于我的编译器,long 和 float 都是 32 位。

有谁知道为什么这不起作用?当我收到要处理的代码时,它看起来是正确的,而且它似乎是一个常见的在线解决方案,我只是被难住了。

最佳答案

确实,这是一个字节序问题:

#include <stdio.h>
#include <stdint.h>

int main()
{
    union {
        uint8_t bytes[4];
        float f;
    } fun1 = { .bytes = { 0x41, 0xd7, 0xd1, 0xe1} }, fun2 = { .bytes = { 0xe1, 0xd1, 0xd7, 0x41} };

    printf("%f\n%f\n", fun1.f, fun2.f);

    return 0;
}

这打印:

-483860023749617123328.000000
26.977480

关于c++ - 将字节数组转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17732630/

相关文章:

c++ - 智能指针 - 堆栈分配变量的 unique_ptr

C - 在 Visual Studio 2012 中使用 scanf_s 打印字符时出错

c - 无法从 .gdbinit 获取文件源

c - strcat 追加多于分配给 array[ ]

java - 必须在列表中使用的参数的通用方法中未经检查的强制转换警告

java - 将字符串转换为整数成员,可能吗?

c++ - Qt Creator(设计器): Single text line with horizontal scrollbar

c++ - 如何从构造函数参数初始化模板成员数组?

c++ - 从 C++ 中的字符串中删除非整数

c++ - Valgrind 在使用 API 时报告内存泄漏