将字节数组转换为float

Ste*_*ven 7 c c++ casting

我有一个程序需要占用4个字节并将它们转换为IEEE-754浮点数.字节不按顺序传输,但我可以把它们按顺序放回去.我的问题是把它们扔到浮子上.代码的相关部分:

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

lWhole很长,stevenFloat是一个漂浮.当调试我可以看到,我分配给字节数组中的值被正确地存储,然而的值stevenFloatlWhole不正确.它们似乎悬停在接近0或接近最大浮点数/长值的位置.使用我的编译器,long和float都是32位.

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

小智 10

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

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

这打印:

-483860023749617123328.000000
26.977480
Run Code Online (Sandbox Code Playgroud)

  • @triclosan也许是因为`-483860023749617123328.000000`在物理上是不可能的,无论是摄氏度,华氏度还是开尔文度? (6认同)
  • @ H2CO3:也许用picokelvin测量太阳中心的温度...... (3认同)