CRC-CCITT校验算法问题
最近用DMR协议其中用到了CRC-CCITT校验算法,协议中关于其描述如下
Consider the n data bits as the coefficients of a polynomial M(x) of degree n-1, associating the MSB of the zero-th octet
with xn-1 and the LSB of the last octet with x0. Define the generator polynomial, GH(x), and the inversion polynomial,
IH(x).
GH(x) = x16 + x12 + x5 + 1 (B.15)
IH(x) = x15 + x14 + x13 + ... + x2 + x + 1 (B.16)
The CRC polynomial, FH(x), is then computed from the formula:
FH(x) = (x16 M(x) mod GH(x)) + IH(x) (B.17)
modulo 2, i.e. in GF(2).
The coefficients of FH(x) are placed in the CRC field with the MSB of the zero-th octet of the CRC corresponding to
x15 and the LSB of the next octet of the CRC corresponding to x0. For the CRC-CCITT calculation the initial remainder
shall be 000016.
我从网上找了CRC-CCITT的算法程序如下
void crc16(unsigned char d[], int len){ unsigned char b = 0; unsigned short crc = 0xffff; int i, j; for(i=0; i<len; i++) { for(j=0; j<8; j++) { b = ((d[i]<<j)&0x80) ^ ((crc&0x8000)>>8); crc<<=1; if(b!=0) crc^=0x1021; } } crc = ~crc; printf("crc: 0x%.4X ", crc);}