16進値のNSStringがあります
NSString* someString = @"AAB827EB5A6E225CAA
b(2番目の文字)から2(-5文字)に抽出したい
抽出されたすべての文字を追加すると、結果として5Cを見つける必要があります(-4および-3文字)
私はこれを試しました:
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);
}
しかし、ログは
16進数:(98、56、50、55、101、98、53、97、54、101、50、50、)
私はそれを文字列に変換してから計算のためにintに変換しようとしましたが、変換を回避して16進数で続行できる場合は、
手伝ってくれてありがとう
コードはおそらくさらに単純化される可能性がありますが、1つの可能性があります。
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]);
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加