2013-07-18 44 views
7

我有一个程序需要占用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; 

lWhole是一项长期而stevenFloat是一个浮动。调试时,我可以看到我分配给字节数组的值被正确存储,但是stevenFloatlWhole的值不正确。他们似乎悬停接近0,或接近最大浮动/长期价值。 long和float与我的编译器都是32位。

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

+0

你确定他们被转移出去的订单?当我把'0x41d7d1e1'放入一个十六进制浮点转换器时,我得到了〜27,这看起来好像是一个很好的数字。 –

+5

排序问题? – 2013-07-18 19:53:55

+0

您希望从0xD1E141D7获得什么? – triclosan

回答

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

此打印:

-483860023749617123328.000000 
26.977480 
+0

你是怎么认定'-483860023749617123328.000000'好于'26.977480' – triclosan

+0

他没有,他只是提出了两种选择供作者决定...... –

+6

@triclosan也许是因为“-483860023749617123328.000000”是物理上不可能的,无论是摄氏度,华氏度还是开尔文度? – 2013-07-18 20:03:10