Possible Duplicate:
Objective C parse hex string to integer
I need the integer value of a NSString representing hex number. For example how do I get the int value (10) of the NSString @"A"?
Possible Duplicate:
Objective C parse hex string to integer
I need the integer value of a NSString representing hex number. For example how do I get the int value (10) of the NSString @"A"?
{
int value;
[[NSScanner scannerWithString @"A"] scanHexInt: &value];
// use value here
}
That would be the simplest code. The method scanHexInt returns a Bool indicating success which you'd want to handle.
You can use the sscanf
with the %
format specifier to parse it as a hexadecimal integer:
NSString *str = @"A";
...
int value;
if (sscanf([str UTF8String], "%x", &value) == 1)
{
// Parsing succeeded
}
else
{
// Parsing failed, handle error
}
You do have to be a bit careful with NSStrings because they can contain Unicode characters. Be sure to iterate over the string character by character and make sure each one is a valid hexadecimal literal, i.e. a character in the set 0-9,a-f,A-F.
Having done that (you can use the NSString method characterAtIndex: to look at individual characters), then it's a fairly easy thing to use the fact that the ASCII / UTF-8 standards order the digits and letters sequentially to your advantage.
Specifically, any digit character subtracted from the digit character '0' will return its integer value. Likewise, if you subtract 'a' from 'a'-'f', or 'A' from 'A'-'F' then add 10, you get the integer version (10-15) of the hexadecimal character.
unichar a = [@"A" characterAtIndex: 0];
if ( a >= '0' && a <= '9' ) a -= '0';
else if ( a >= 'a' && a <= 'z' ) a = ( a - 'a' ) + 10;
else if ( a >= 'A' && a <= 'Z' ) a = ( a - 'A' ) + 10;
else { /* error, raise exception or whatever */ };
// now a == 10 (0x0A)