我正在尝试将具有十六进制值的 nsstring 转换为浮点值。
NSString *hexString = @"3f9d70a4";
浮点值应该是= 1.230
.
我尝试解决的一些方法是:
1.NSScanner
-(unsigned int)strfloatvalue:(NSString *)str
{
float outVal;
NSString *newStr = [NSString stringWithFormat:@"0x%@",str];
NSScanner* scanner = [NSScanner scannerWithString:newStr];
NSLog(@"string %@",newStr);
bool test = [scanner scanHexFloat:&outVal];
NSLog(@"scanner result %d = %a (or %f)",test,outVal,outVal);
return outVal;
}
结果:
string 0x3f9d70a4
scanner result 1 = 0x1.fceb86p+29 (or 1067282624.000000)
2.铸造指针
NSNumber * xPtr = [NSNumber numberWithFloat:[(NSNumber *)@"3f9d70a4" floatValue]];
结果:3.000000