NSScanner可以通过一定数量的字符进行解析吗?

时间:2010-02-23 14:35:54

标签: objective-c iphone cocoa-touch

我有一堆数据采用下面列出的格式,我需要将其从2位十六进制转换为各自的整数值。我可以为NSScanner指定任何一次转换需要2个字符的内容。或者我是否需要手动打破字符串(例如“D8”“BE”......)或重新格式化以包含NSScanner将理解的分隔符(例如@“D8 BE 98 31 BC 96 17 EB 29 54”?

注意:这是我尝试做的一个例子(它不起作用)

NSString *fakeData = [[NSString alloc] initWithString:@"D8BE9831BC9617EB2954"];
NSScanner *responseScanner = [NSScanner scannerWithString:fakeData];
unsigned int intValue;

while([responseScanner isAtEnd] == NO) {
    [responseScanner scanHexInt:&intValue];
    NSLog(@"HEX : %d", intValue);       
}

这:一个答案(这是有效的)

NSString *fakeData = [[NSString alloc] initWithString:@"D8 BE 98 31 BC 96 17 EB 29 54"];
NSScanner *responseScanner = [NSScanner scannerWithString:fakeData];
unsigned int intValue;

while([responseScanner isAtEnd] == NO) {
    [responseScanner scanHexInt:&intValue];
    NSLog(@"HEX : %d", intValue);       
}

EDIT_001

非常感谢您的提升,NSScanner当然非常有用,只是遗憾的是您无法指定要抓取的十六进制数字的位数。

NSString *fakeData = [[NSString alloc] initWithString:@"D8BE9831BC9617EB2954"];
unsigned int intValue;

for(unsigned int location=0; location<[fakeData length]-1; location+=2) {
    NSString *subString = [fakeData substringWithRange:NSMakeRange(location, 2)];
    NSScanner *scanner = [NSScanner scannerWithString:subString];
    [scanner scanHexInt:&intValue];
    NSLog(@"LOCATION(%d) = %d", location, intValue);
}
[fakeData release];

加里

1 个答案:

答案 0 :(得分:1)

不,NSScanner没有任何机制可以扫描特定数量的十六进制字符。

您可以一次对数据2个字符串进行子串,并在2-char字符串上使用NSScanner:

NSString *fakeData = [[NSString alloc] initWithString:@"D8BE9831BC9617EB2954"];
unsigned int intValue;

for (unsigned int start = 0; start+2 <= [fakeData length]; start += 2) {
  NSRange nextRange = NSMakeRange(start, 2);
  NSString *nextByte = [fakeData substringWithRange:nextRange];
  NSScanner *responseScanner = [NSScanner scannerWithString:nextByte];
  [responseScanner scanHexInt:&intValue];
  NSLog(@"HEX : %d", intValue);       
}