本人開發(fā)的都是和藍(lán)牙有關(guān)在程序中 經(jīng)常要用到異或運(yùn)算
現(xiàn)在給大家羅列出來(lái)
1校驗(yàn)位異或 傳入16進(jìn)制串
-(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(@"校驗(yàn)異或的結(jié)果%@",[str hexToBytes]);
//NSLog(@"進(jìn)行校驗(yàn)運(yùn)算");
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;
}
因?yàn)樵谑撬{(lán)牙開發(fā)所以經(jīng)常要對(duì)data進(jìn)行拼接所以傳入用可變的data