Convert Hex Value Stored As NSString To Integer

If you have a hex value that is stored in an NSString object and need to convert the value into an integer, the NSScanner object can be of great help.

Let’s say for example that you need convert the string “0xABCD” to its integer equivalent. Or maybe you are working with values that are related to a color selection, then you may have a value in hex that looks like this “#12BC99.” In either case, the method below will convert the NSString using NSScanner and return an integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (unsigned int)intFromHexString:(NSString *) hexStr
{
  unsigned int hexInt = 0;
 
  // Create scanner
  NSScanner *scanner = [NSScanner scannerWithString:hexStr];
 
  // Tell scanner to skip the # character
  [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];
 
  // Scan hex value
  [scanner scanHexInt:&hexInt];
 
  return hexInt;
}

Notice on line 9 that we request the scanner to skip the ‘#’ character during scanning:

Let’s look at the output of a few values:

NSString *str = @"0xABCD";
NSString *str1 = @"#EED9C4";
 
NSLog(@"hex int value: %d", [self intFromHexString:str]);
NSLog(@"hex int value: %d", [self intFromHexString:str1]);
NSLog(@"hex int value: %d", [self intFromHexString:@"happyhappyjoyjoy"]);

The output is shown below:

hex int value: 43981
hex int value: 15653316
hex int value: 0

Obviously, if you know that you’ll never have a string with a ‘#’ you can remove that code.