1.利用union进行数据转换
union即为联合,它是一种特殊的类。通过关键字union进行定义,可以进行数据转换
16进制字符串字节转化为十进制数
typedef union DATA_TO_BYTE { uint16_t data16; unsigned char b[2]; }TO_TWO_BYTE; TO_TWO_BYTE x; x.b[0] = (unsigned char)0x00;//低8位 x.b[1] = (unsigned char)0x16;//高8位 std::cout<<x.data16<<std::endl;
输出结果为5632
2.四字节与float转换
参考链接:https://blog.csdn.net/senkkes/article/details/50353316
// char to float char sBuf[4]; sBuf[0] = 0xc9; sBuf[1] = 0x4f; sBuf[2] = 0x7d; sBuf[3] = 0x43; float zx = *(float *)(sBuf); std::cout<< zx <<std::endl;//终端输出为253.312 // float to char float wTemp = 50; char sBuf1[4]; char* temp; memset(sBuf1, 0, sizeof(sBuf1)); temp = (char *)(&wTemp); sBuf1[0] = temp[0]; sBuf1[1] = temp[1]; sBuf1[2] = temp[2]; sBuf1[3] = temp[3];