如何扫描十六进制整数,复数?

时间:2015-08-18 05:42:53

标签: objective-c hex

我想从最多包含20个数字的空格分隔字符串中解析多个十六进制整数:

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];

但是scanHexInt似乎只扫描一个值。有没有更简洁的方法将字符串扫描成值数组?

scanHexInt docs

Objective-C parse hex string to integer

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以使用已有的大多数代码,只需在循环中调整scanLocation

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);
}