2016-04-11 6 views
0

i haben eine NSString mit HexadezimalwertIOS hex zusätzlich

NSString* someString = @"AAB827EB5A6E225CAA 

i von B zu extrahieren (die zweite char) bis 2 (-5 char)

eine Addition aller extrahierten char machen und ich habe die 5C als Ergebnis finden (-4 und -3 char)

ich dies versucht haben:

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

aber das Protokoll ist

hex: ( 98, 56, 50, 55, 101, 98, 53, 97, 54, 101, 50, 50)

Ich habe versucht, es in String zu konvertieren, dann Int für die Berechnung, aber wenn ich Konversion vermeiden und mit Hex fortfahren kann, würde ich

bevorzugen 10

Dank für Hilfe

Antwort

1

Der Code wahrscheinlich simplifed noch mehr aber eine Möglichkeit sein könnte:

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]); 
} 
+0

funktioniert perfekt Dank – Ogyme