views:

83

answers:

1

I have a pile of data in the format listed below that I need to convert from 2-digit hex to their respective integer values. Is there anything that I can specify to NSScanner that will take 2 characters at a time for conversion. Or will I need to either break the string up manually (e.g. "D8" "BE" ...) or reformat it to include a delimiter that NSScanner will understand (e.g. @"D8 BE 98 31 BC 96 17 EB 29 54"?

NOTE: This is an example of what I am trying to do (it does not work)

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

THIS: Would be one answer (this works)

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

Thank you very much for the heads up, NSScanner is certainly very useful, just a shame you can't specify how many digits make up the hex number you want to grab.

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

gary

+1  A: 

No, NSScanner does not have any mechanism for scanning a specific number of hex characters.

You could substring the data 2 chars at a time and use NSScanner on the 2-char strings:

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