四字节转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));