将十六进制字符串转换为IEEE 754浮点数 [英] Convert Hex string to IEEE 754 float

查看:486
本文介绍了将十六进制字符串转换为IEEE 754浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将具有十六进制值的nsstring转换为float值.

I am trying to convert a nsstring with hex values into a float value.

NSString *hexString = @"3f9d70a4";

浮点值应为= 1.230.

我尝试解决此问题的一些方法是:

Some ways I have tried to solve this are:

1.NSScanner

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

推荐答案

您所拥有的不是十六进制浮点数",而是由%a字符串格式产生并由scanHexFloat:扫描的,而是a的十六进制表示形式. 32位浮点值-即实际位.

What you have is not a "hexadecimal float", as is produced by the %a string format and scanned by scanHexFloat: but the hexadecimal representation of a 32-bit floating-point value - i.e. the actual bits.

要将其转换回C语言中的浮点数,需要弄乱类型系统-使您能够访问组成浮点值的字节.您可以使用union:

To convert this back to a float in C requires messing with the type system - to give you access to the bytes that make up a floating-point value. You can do this with a union:

typedef union { float f; uint32_t i; } FloatInt;

此类型类似于struct,但字段彼此重叠.您应该了解,进行这种操作需要了解存储格式,了解字节顺序等.请勿轻易这样做.

This type is similar to a struct but the fields are overlaid on top of each other. You should understand that doing this kind of manipulation requires you understand the storage formats, are aware of endian order, etc. Do not do this lightly.

现在具有以上类型,您可以扫描十六进制整数并将结果字节解释为浮点数:

Now you have the above type you can scan a hexadecimal integer and interpret the resultant bytes as a floating-point number:

FloatInt fl;
NSScanner *scanner = [NSScanner scannerWithString:@"3f9d70a4"];

if([scanner scanHexInt:&fl.i])        // scan into the i field
{
    NSLog(@"%x -> %f", fl.i, fl.f);   // display the f field, interpreting the bytes of i as a float
}
else
{
    // parse error
}

这可行,但再次仔细考虑您在做什么.

This works, but again consider carefully what you are doing.

HTH

这篇关于将十六进制字符串转换为IEEE 754浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆