Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hex string to long

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

like image 434
Hua-Ying Avatar asked Dec 09 '09 16:12

Hua-Ying


3 Answers

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];
like image 129
ttvd Avatar answered Nov 09 '22 00:11

ttvd


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

like image 37
Joshua Nozzi Avatar answered Nov 09 '22 00:11

Joshua Nozzi


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);
like image 41
hokkuk Avatar answered Nov 08 '22 23:11

hokkuk