1

I'm trying using the following code:

float fValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:@"0x41CC8937"];
[scanner scanHexFloat:&fValue];

Hex 0x41CC8937 = float 25.567.

But I'm getting fValue = 0x4E839912 (float 1103923456.000000), Why?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
TESTer
  • 55
  • 6

1 Answers1

3

scanHexFloat expects a "Hexadecimal Floating-Point Constant", you can read more about that here: http://www.exploringbinary.com/hexadecimal-floating-point-constants/.

What you have it the binary representation of the 32-bit floating point value. You can read that with scanHexInt and use a union to interpret the number as float:

union {
    float fValue;
    unsigned int iValue;
} u;
NSScanner *scanner = [NSScanner scannerWithString:@"0x41CC8937"];
[scanner scanHexInt:&u.iValue];
NSLog(@"%f", u.fValue);

Output: 25.566999

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thank You! Invoke this method with NULL as result to simply scan past a hexadecimal float representation. How does this work? – TESTer May 17 '13 at 17:52
  • @TESTer: If you are not interested in the value and just want to skip a hexadecimal number in the input, then you can call `[scanner scanHexInt:NULL]`. – Martin R May 17 '13 at 17:55