公司在做物聯(lián)網(wǎng)這塊,然后硬件工程師今天告訴我要給藍牙發(fā)送十六進制,來校驗時間,需要用到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; //選擇數(shù)據(jù)要計算CRC的起始位
? ? intend = (uint16_t)[selflength];//選擇數(shù)據(jù)要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;
}