一、问题出现场景
产品使用的一家可燃气检测传感器,会传递给我一个已经是浮点数的四字节数据,但是我在编写程序时使用实际的浮点数数据

注:浓度值数据类型为浮点型,占4个字节;通讯时 先低(16位)后高(16位),高字节在前,低字节在后。(比如浮点数23.56,在内存中为41 BC 7A E1,通讯时传输顺序:7A E1 41 BC。)

二、进行四字节的浮点数转换
直接上代码:【直接可以得到浮点数】

#include <iostream>
 
float convertBytesToFloat(unsigned char* com_r) {
    float sum0 = 0.0;
    unsigned char* p0 = (unsigned char*)&sum0;
 
    *p0 = com_r[1];
    *(p0 + 1) = com_r[0];
    *(p0 + 2) = com_r[3];
    *(p0 + 3) = com_r[2];
 
    return sum0;
}
 
int main() {
    unsigned char com_r[10];
    com_r[0] = 0x00;
    com_r[1] = 0x00;
    com_r[2] = 0x42;
    com_r[3] = 0x78;
 
    float result = convertBytesToFloat(com_r);
 
    std::cout << "Result: " << result << std::endl;
 
    return 0;
}
AI写代码
cpp
运行

三、将浮点数换成四字节数据
直接行代码:【注意数据传递顺序进行调整】

#include <iostream>
#include <cstdint>
 
int main() {
    float value = 6.0;
    uint32_t* floatPtr = reinterpret_cast<uint32_t*>(&value);
    uint32_t floatValue = *floatPtr;
 
    uint8_t bytes[4];
    for (int i = 0; i < 4; i++) {
        bytes[i] = (floatValue >> (8 * i)) & 0xFF;
    }
 
    std::cout << "Byte 1: " << std::hex << static_cast<int>(bytes[0]) << std::endl;
    std::cout << "Byte 2: " << std::hex << static_cast<int>(bytes[1]) << std::endl;
    std::cout << "Byte 3: " << std::hex << static_cast<int>(bytes[2]) << std::endl;
    std::cout << "Byte 4: " << std::hex << static_cast<int>(bytes[3]) << std::endl;
 
    return 0;
}
AI写代码
cpp
运行

关于浮点数的知识,大佬已经讲的很清楚,大家可以参考

IEEE754标准: 一 , 浮点数在内存中的存储方式 - 知乎 (zhihu.com)
https://zhuanlan.zhihu.com/p/343033661
————————————————
版权声明:本文为CSDN博主「纸上苍生」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/kingboj/article/details/135117025

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐