公司在做物联网这块,然后硬件工程师今天告诉我要给蓝牙发送十六进制,来校验时间,需要用到CRC16-CCITT-FALSE校验,当时我就懵了,第一次做蓝牙,第一次听说CRC16-CCITT-FALSE校验算法,度娘了半天,结果只有Java和C的校验代码,没有OC的校验代码,没办法了,只能把C的代码改成OC的了
- (NSString *)CRCSumString
{
BytecrcByte[2] = {0x00,0x00};
unsignedintcrcInt = [selfcrcData];
memcpy(&crcByte, &crcInt,2);
return[NSStringstringWithFormat:@"%2X%2X", crcByte[0], crcByte[1]];
}
- (unsigned short)crcData{
int start = 0; //选择数据要计算CRC的起始位
intend = (uint16_t)[selflength];//选择数据要CRC计算的范围段
unsigned short crc =0xffff; // initial value
unsignedshort polynomial =0x1021;// poly value
BytecodeKeyByteAry[self.length];
for(inti =0; i
NSData *idata = [self subdataWithRange:NSMakeRange(i, 1)];
codeKeyByteAry[i] =((Byte*)[idatabytes])[0];
}
for(intindex = start; index < end; index++){
Byteb = codeKeyByteAry[index];
for(inti =0; i <8; i++) {
Booleanbit = ((b >> (7- i) &1) ==1);
Booleanc15 = ((crc >>15&1) ==1);
crc <<=1;
if(c15 ^ bit)
crc ^= polynomial;
}
}
crc &=0xffff;
returncrc;
}
网友评论