将字节数组强制转换为浮点
Cast byte array to float
我有一个程序,需要接收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;
CCD_ 1是长的,而CCD_。调试时,我可以看到我分配给字节数组的值存储正确,但stevenFloat
和lWhole
的值不正确。它们似乎徘徊在0附近,或接近最大浮动/长值。在我的编译器中,long和float都是32位。
有人知道为什么不起作用吗?当我收到要处理的代码时,它在我看来是正确的,而且它似乎是一个常见的在线解决方案,我只是被难住了。
事实上,这是一个endianness问题:
#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("%fn%fn", fun1.f, fun2.f);
return 0;
}
此打印:
-483860023749617123328.000000
26.977480
相关文章:
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 将字节数组转换为带有字节序问题的指针
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 如何在连接器 C++ 中将原始字节转换为字符串
- 如何在C++(Arduino)中将浮点数组转换为字节数组
- 将字节数组转换为多维数组
- C++如何将字符数组转换为字节向量(向量<byte>)
- 如何在C++中将字节向量(std::vector<uint8_t>)转换为不同的uint32_t,uint16_t和uint8_t变量
- 将字符串转换为无符号字符数组/字节数组
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- 将以 null 结尾的字节字符串转换为原始字符串文本
- 正在转换结构数据的字节序
- 如何将 CString 转换为字节 [] 数组?
- 一种将 Dart 中的字节数据转换为 C++ 中的无符号字符*的有效方法?
- 使用 ESP8266/8285 将字符串从 Web 服务器转换为字节数组
- 编译时将字符*转换为字节
- 将字节数组转换为对象C++ |C++中的 C# 位转换器
- C++转换字节
- 将整型转换字节中的字节更改为整数
- c++从字符串化字节转换字节数组