typedef union
{
float float_data;
char hex_data[4];
}float2hex;
通过联合体占用成员最大内存的机制转换float。
float hex_2_float(char *buf)
{
float2hex temp;
if(buf !=NULL)
{
temp.hex_data[0] = buf[3];
temp.hex_data[1] = buf[2];
temp.hex_data[2] = buf[1];
temp.hex_data[3] = buf[0];
}
return temp.float_data;
}
输入一个4字节的buf[4]={0x43,0x5B,0xE6,0x66};输出float temp=219.9。
void float_2_hex(float data,char *buf)
{
float2hex temp;
temp.float_data = data;
buf[0] = temp.hex_data[3];
buf[1] = temp.hex_data[2];
buf[2] = temp.hex_data[1];
buf[3] = temp.hex_data[0];
}
输入浮点数data,存储16进制的4字节数组buf[4]。
例如输入219.9,temp_buf[4],输出temp_buf[4]={0x43,0x5B,0xE6,0x66}。
由于使用STM32,该芯片是小端模式,所以程序中转换了顺序,使用时不需要调转顺序直接用即可。
注意点,浮点数不要用==做比较,浮点数存在精度问题,无法准确相等。