将4个原始字节转换为32位浮点 [英] Converting 4 raw bytes into 32-bit floating point

查看:299
本文介绍了将4个原始字节转换为32位浮点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



eeprom存储器(0-4)中的4个字节是: B4 A2 91 4D

和PC(VS Studio)正确重建为3.054199 * 10 ^ 8(我知道的浮点值应该在那里)



现在我把这个eeprom从一个8位的Arduino中读取出来,所以不知道它是编译器还是平台的东西,但是当我尝试读取4个字节到一个32位的字节时,然后将它转换为一个浮点数,我得到的值甚至不是很接近。

假设转换不能用标准的ansi- c编译器,如何将4个字节手动解析为浮点数?

解决方案

最安全的方法是,由于编译器的优化也可以使用 memcpy

  uint32_t dword = 0x4D91A2B4; 
float f;
memcpy(& f,& dw,4);

演示: http:/ /ideone.com/riDfFw


I'm trying to re-construct a 32-bit floating point value from an eeprom.

The 4 bytes in eeprom memory (0-4) are : B4 A2 91 4D

and the PC (VS Studio) reconstructs it correctly as 3.054199 * 10^8 (the floating point value I know should be there)

Now I'm moving this eeprom to be read from an 8-bit Arduino, so not sure if it's compiler/platform thing, but when I try reading the 4 bytes into a 32-bit dword, and then typecast it to a float, the value I get isn't even close.

Assuming the conversion can't be done automatically with the standard ansi-c compiler, how can the 4 bytes be manually parsed to be a float?

解决方案

The safest way, and due to compiler optimization also as fast as any other, is to use memcpy:

uint32_t dword = 0x4D91A2B4;
float f;
memcpy(&f, &dw, 4);

Demo: http://ideone.com/riDfFw

这篇关于将4个原始字节转换为32位浮点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆