四字节转float函数

函数

 1 //四个字节转换成folat型
 2 float FourBytesToFloat (UCHAR byte1,UCHAR byte2,UCHAR byte3,UCHAR byte4)
 3 {
 4     int bits=( byte1 << 24 ) + ( byte2 << 16 ) + ( byte3 << 8) + byte4;
 5     int s = ( bits >> 31 ) == 0 ? 1 : -1;
 6     int e = ( bits >> 23 ) & 0xff;
 7     int m = ( e == 0 ) ?
 8         ( bits & 0x7fffff ) << 1 :
 9     ( bits & 0x7fffff ) | 0x800000;
10     return s * m * ( float ) pow( 2, e - 150 );    
11 }

调用

CString strTemp;
strTemp = strRecv.Right(2);
BYTE b1 = strtol(strTemp, NULL, 16);
strTemp = strRecv.Mid(strRecv.GetLength() - 4, 2);
BYTE b2 = strtol(strTemp, NULL, 16);
strTemp = strRecv.Mid(strRecv.GetLength() - 6, 2);
BYTE b3 = strtol(strTemp, NULL, 16);
strTemp = strRecv.Mid(strRecv.GetLength() - 8, 2);
BYTE b4 = strtol(strTemp, NULL, 16);
float fValue = (FourBytesToFloat(b4, b3, b2, b1));

 方法2:

函数

 1 float Bit4ToFloat(int a, int b, int c, int d)
 2 {
 3     float freq;
 4     unsigned char test[4] = { a, b, c, d };  //输入的数据,高字节到低字节排列
 5     unsigned char* Modbus_HoldReg[1000];       //保持寄存器指针,一个字节
 6 
 7     //第一步:指针首先指向地址
 8     Modbus_HoldReg[20] = ((unsigned char*)(&freq)) + 3;  //低地址指向高位
 9     Modbus_HoldReg[21] = ((unsigned char*)(&freq)) + 2;
10     Modbus_HoldReg[22] = ((unsigned char*)(&freq)) + 1;
11     Modbus_HoldReg[23] = ((unsigned char*)(&freq)) + 0;  //高地址指向低位
12 
13     //第二步:将数据映射到指定地址
14     *Modbus_HoldReg[20] = test[0];
15     *Modbus_HoldReg[21] = test[1];
16     *Modbus_HoldReg[22] = test[2];
17     *Modbus_HoldReg[23] = test[3];
18 
19     return freq;
20 }

调用

float ff = Bit4ToFloat(0x43, 0x6B, 0x5A, 0x2F);//结果235.352280

 

posted @ 2022-01-28 11:15  ckrgd  阅读(1317)  评论(0编辑  收藏  举报