iOS 关于异或运算

本人开发的都是和蓝牙有关在程序中 经常要用到异或运算

现在给大家罗列出来

1校验位异或 传入16进制串

-(NSData*)getcheckSum_BLE:(NSString*)byteStr

{

intlength = (int)byteStr.length/2;

NSData*data = [selfhexstrToBytes:byteStr];

Byte*bytes = (unsignedchar*)[databytes];

Bytesum =0;

for(inti =0;i

{

sum^=bytes[i];

}

NSString*str = [NSStringstringWithFormat:@"%@%@",byteStr,[selfToHex_BLE:sum]];

//NSLog(@"校验异或的结果%@",[str hexToBytes]);

//NSLog(@"进行校验运算");

return[self  hexstrToBytes:str];

}

-(NSData*)hexstrToBytes:(NSString*)lenstr

{

NSMutableData* data = [NSMutableDatadata];

intidx;

for(idx =0; idx+2<= lenstr.length; idx+=2) {

NSRangerange =NSMakeRange(idx,2);

NSString* hexStr = [lenstrsubstringWithRange:range];

NSScanner* scanner = [NSScannerscannerWithString:hexStr];

unsignedintintValue;

[scannerscanHexInt:&intValue];

[dataappendBytes:&intValuelength:1];

}

returndata;

}


2 和0X5A异或

-(NSData*)yihuo0X5A:(NSMutableData*)dataresult

{

Byte*byte1 = (unsignedchar*)[dataresultbytes];

Bytesum =0x5A;

for(inti =0; i

{

byte1[i]^=sum;

}

NSData*data1 = [[NSDataalloc]initWithBytes:byte1length:dataresult.length];

NSString*string = [[NSStringalloc]initWithBytes:byte1length:dataresult.lengthencoding:NSUTF8StringEncoding];

returndata1;

}

因为在是蓝牙开发所以经常要对data进行拼接所以传入用可变的data

你可能感兴趣的:(iOS 关于异或运算)