Reputation: 13
i have an NSString with hex value
NSString* someString = @"AAB827EB5A6E225CAA
i want to extract from b (the second char) to 2 (-5 char)
make an addition of all extracted char and i have to find the 5C as result (-4 and -3 char)
i have tried this :
NSMutableArray *hex = [[NSMutableArray alloc]init];
unichar firstChar = [[someString uppercaseString] characterAtIndex:0];
unichar seconChar = [[someString uppercaseString] characterAtIndex:1];
unichar lastChar = [[someString uppercaseString] characterAtIndex:[print length]-1];
unichar beforeLastChar = [[someString uppercaseString] characterAtIndex:[print length]-2];
if (firstChar == 'A' && seconChar == 'A' && lastChar =='A' && beforeLastChar=='A') {
for (int i=2;i< [print length]-4; i++) {
NSString *decim =[NSString stringWithFormat:@"%hu",[someString characterAtIndex:i]];
[hex addObject:decim];
}
NSLog(@"hex : %@",hex);
}
but the log is
hex : ( 98, 56, 50, 55, 101, 98, 53, 97, 54, 101, 50, 50, )
i've tried to covert it to string then int for calculation but if i can avoid conversion and continue with hex i would prefer
thanks for help
Upvotes: 1
Views: 358
Reputation: 130092
The code could be probably simplifed even more but one possibility:
NSString *someString = @"AAB827EB5A6E225CAA";
// I have improved a bit your check for prefix and suffix
if ([someString hasPrefix:@"AA"] && [someString hasSuffix:@"AA"]) {
NSMutableArray *hexNumbers = [[NSMutableArray alloc] init];
for (int i = 2; i < [someString length] - 4; i++) {
unichar digit = [someString characterAtIndex:i];
NSUInteger value;
// we have to convert the character into its numeric value
// we could also use NSScanner for it but this is a simple way
if (digit >= 'A') {
value = digit - 'A' + 10;
} else {
value = digit - '0';
}
// add the value to the array
[hexNumbers addObject:@(value)];
}
NSLog(@"hex : %@", hexNumbers);
// a trick to get the sum of an array
NSNumber *sum = [hexNumbers valueForKeyPath:@"@sum.self"];
// print the sum in decadic and in hexadecimal
NSLog(@"Sum: %@, in hexa: %X", sum, [sum integerValue]);
}
Upvotes: 1