16

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

Quinn Taylor
  • 44,553
  • 16
  • 113
  • 131
Hua-Ying
  • 3,166
  • 4
  • 23
  • 25
  • 3
    This is not a duplicate of http://stackoverflow.com/questions/1870475, which is about converting the hex digits to *a string*. – Peter Hosey Dec 09 '09 at 19:10

3 Answers3

41

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];
ttvd
  • 1,665
  • 1
  • 18
  • 16
11

See NSScanner's scanHex...: methods. That'll get you the primitive that you can wrap in an NSNumber.

Joshua Nozzi
  • 60,946
  • 14
  • 140
  • 135
7

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);
hokkuk
  • 675
  • 5
  • 21