0

I want to parse multiple hex integers from a space-separated string of up to 20 numbers:

79 1A 03 00 09 21 22 AA BB CC DD EE FF A1 A2 A3 A4 A5 A6 A7

unsigned result = 0;
NSScanner *scanner = [NSScanner scannerWithString:@"79 1A 03 00"];

[scanner setScanLocation:0];
[scanner scanHexInt:&result];

But scanHexInt seems to only scan a single value. Is there a cleaner way to scan a string into an array of values?

scanHexInt docs

Objective-C parse hex string to integer

Community
  • 1
  • 1
tarabyte
  • 17,837
  • 15
  • 76
  • 117

2 Answers2

0
  NSArray *numberTokens = [text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];
  for (NSString* token in numberTokens) {
    if (0 < token.length) {
      NSLog(@"%@: %i", token, token.intValue);
    }
  }
tarabyte
  • 17,837
  • 15
  • 76
  • 117
0

You can use most of the code you already have, simply adjust the scanLocation in a loop:

NSString *string = @"79 1A 03 00 09 21 22 AA BB CC DD EE FF A1 A2 A3 A4 A5 A6 A7";
unsigned result = 0;
NSScanner *scanner = [NSScanner scannerWithString:string];

// Skip ahead 3 characters (2 hex digits + 1 space)
// after each iteration.
for (NSUInteger i=0; i < string.length; i+=3) {
    [scanner setScanLocation:i];
    [scanner scanHexInt:&result];

    NSLog(@"%d", result);
}
Steve Wilford
  • 8,894
  • 5
  • 42
  • 66