僅供參考,比較low
- (void) xorVerify{
//字符串
//轉(zhuǎn)data
//轉(zhuǎn)int運(yùn)算,得到結(jié)果
NSMutableArray * m_arr = [NSMutableArray array];
[m_arr addObjectsFromArray:@[@"AA",@"55",@"0F",@"02",@"83"]];
//計(jì)算校驗(yàn)碼
NSMutableString * str_m = [NSMutableString string];
int a[5];
int j = 0;
//字符串轉(zhuǎn)成16進(jìn)制
for (NSString * hex in m_arr) {
[str_m appendString:hex];
NSData * data = [self convertHexStrToData:hex];
int i = 0;
[data getBytes: &i length: sizeof(i)];
printf("%x\n", i); //按十六進(jìn)制輸出結(jié)果
a[j] = i;
j++;
}
int result = 0;
//異或計(jì)算
for (int i = 0; i < m_arr.count; i ++) {
//進(jìn)行16進(jìn)制計(jì)算
result = result ^ a[i];
}
printf("異或結(jié)果 : %x\n", result);
}
// 將十六進(jìn)制字符串轉(zhuǎn)換成NSData
+ (NSData *)convertHexStrToData:(NSString *)str {
if (!str || [str length] == 0) {
return nil;
}
NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
NSRange range;
if ([str length] % 2 == 0) {
range = NSMakeRange(0, 2);
} else {
range = NSMakeRange(0, 1);
}
for (NSInteger i = range.location; i < [str length]; i += 2) {
unsigned int anInt;
NSString *hexCharStr = [str substringWithRange:range];
NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
[scanner scanHexInt:&anInt];
NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
[hexData appendData:entity];
range.location += range.length;
range.length = 2;
}
return hexData;
}