Are there any Cocoa classes that will help me convert a hex value in a NSString like 0x12FA
to a long
or NSNumber
? It doesn't look like any of the classes like NSNumberFormatter
support hex numbers.
Thanks, Hua-Ying
Here's a short example of how you would do it using NSScanner:
NSString* pString = @"0xDEADBABE";
NSScanner* pScanner = [NSScanner scannerWithString: pString];
unsigned int iValue;
[pScanner scanHexInt: &iValue];
See NSScanner's scanHex...: methods. That'll get you the primitive that you can wrap in an NSNumber.
here is the other way conversion, a long long int to hex string.
first the hex to long long.
NSString* pString = @"ffffb382ddfe";
NSScanner* pScanner = [NSScanner scannerWithString: pString];
unsigned long long iValue2;
[pScanner scanHexLongLong: &iValue2];
NSLog(@"iValue2 = %lld", iValue2);
and the other way, longlong to hex string...
NSNumber *number;
NSString *hexString;
number = [NSNumber numberWithLongLong:iValue2];
hexString = [NSString stringWithFormat:@"%qx", [number longLongValue]];
NSLog(@"hexString = %@", hexString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With