仅供参考,比较low
- (void) xorVerify{
//字符串
//转data
//转int运算,得到结果
NSMutableArray * m_arr = [NSMutableArray array];
[m_arr addObjectsFromArray:@[@"AA",@"55",@"0F",@"02",@"83"]];
//计算校验码
NSMutableString * str_m = [NSMutableString string];
int a[5];
int j = 0;
//字符串转成16进制
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); //按十六进制输出结果
a[j] = i;
j++;
}
int result = 0;
//异或计算
for (int i = 0; i < m_arr.count; i ++) {
//进行16进制计算
result = result ^ a[i];
}
printf("异或结果 : %x\n", result);
}
// 将十六进制字符串转换成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;
}
网友评论