今天开发遇上了个问题,从蓝牙设备获取的data
数据是<713da442 0600>
,数据格式转化是前4个字节逆序表示浮点数十六进制数据,也就是对应的十六进制数据为:0x42a43d71
,这个值对应十进制浮点数为:82.1200027,转化过程如下:
<713da442 0600>
- (float)transformWithIEEE754ToFloatWithData:(NSData *)data
{
if (!data) {
return 0;
}
Byte *bytes = (Byte *)[data bytes];
NSMutableString *value = [NSMutableString string];
for (int i = 3; i >= 0; i--) {
[value appendString:[NSString stringWithFormat:@"%x", bytes[i]&0xff]];
}
/// value = @"42a43d71"
NSInteger temp = [self numberWithHexString:value];
float result = Hex2Float(temp);
return result;
}
/// 16进制字符串转10进制
- (NSInteger)numberWithHexString:(NSString *)hexString{
const char *hexChar = [hexString cStringUsingEncoding:NSUTF8StringEncoding];
int hexNumber;
sscanf(hexChar, "%x", &hexNumber);
return (NSInteger)hexNumber;
}
#include <stdio.h>
#include <math.h>
//十六进制数转浮点数通用方法
float Hex2Float(NSInteger number)
{
int sign = (number & 0x80000000) ? -1 : 1;//三目运算符
int exponent = ((number >> 23) & 0xff) - 127;//先右移操作,再按位与计算,出来结果是30到23位对应的e
float mantissa = 1 + ((float)(number & 0x7fffff) / 0x7fffff);//将22~0转化为10进制,得到对应的x
return sign * mantissa * pow(2, exponent);
}