📄 crc.lst
字号:
1: /* crc.c
2: /* crc程序,包括两部分,crcInit生成CRC查找表
3: /* crcCompute执行后生成crc校验码
4: /* crcCompute两个参数,一个为起始地址,一个为计算个数,返回值为16bit的整型变量
5: */
6:
7: #define POLYNOMIAL 0x1021 /* crc-ccitt mask */
8: #define INITIAL_REMAINDER 0xFFFF
9: #define FINAL_XOR_VALUE 0x0000
10:
11: typedef unsigned short width;
12:
13: #define WIDTH (8 * sizeof(width))
14: #define TOPBIT (1 << (WIDTH - 1))
15:
16:
17: /*
18: * An array containing the pre-computed intermediate result for each
19: * possible byte of input. This is used to speed up the computation.
20: */
21: width crcTable[256];
22:
23:
24: /**********************************************************************
25: *
26: * Function: crcInit()
27: *
28: * Description: Initialize the CRC lookup table. This table is used
29: * by crcCompute() to make CRC computation faster.
30: *
31: * Notes: The mod-2 binary long division is implemented here.
32: *
33: * Returns: None defined.
34: *
35: **********************************************************************/
36:
37: void crcInit(void)
38: {
39: width remainder;
40: width dividend;
41: int i;
42:
43:
44: /*
45: * Perform binary long division, a bit at a time.
46: */
47: for (dividend = 0; dividend < 256; dividend++)
48: {
49: /*
50: * Initialize the remainder.
51: */
52: remainder = dividend << (WIDTH - 8);
53:
54: /*
55: * Shift and XOR with the polynomial.
56: */
57: for (i = 0;i < 8; i++)
58: {
59: /*
60: * Try to divide the current data bit.
61: */
62: if (remainder & TOPBIT)
63: {
64: remainder = (remainder << 1) ^ POLYNOMIAL;
65: }
66: else
67: {
68: remainder = remainder << 1;
69: }
70: }
71:
72: /*
73: * Save the result in the table.
74: */
75: crcTable[dividend] = remainder;
76: }
77:
78: } /* crcInit() */
79:
80:
81: /**********************************************************************
82: *
83: * Function: crcCompute()
84: *
85: * Description: Compute the CRC checksum of a binary message block.
86: *
87: * Notes: This function expects that crcInit() has been called
88: * first to initialize the CRC lookup table.
89: *
90: * Returns: The CRC of the data.
91: *
92: **********************************************************************/
93: unsigned int crcCompute(unsigned char * message, unsigned int nBytes)
94: {
95: unsigned int offset;
96: unsigned char byte;
97: width remainder = INITIAL_REMAINDER;
98:
99:
100: /*
101: * Divide the message by the polynomial, a byte at time.
102: */
103: for (offset = 0; offset < nBytes; offset++)
104: {
105: byte = (remainder >> (WIDTH - 8)) ^ message[offset];
106: remainder = crcTable[byte] ^ (remainder << 8);
107: }
108:
109: /*
110: * The final remainder is the CRC result.
111: */
112: return (remainder ^ FINAL_XOR_VALUE);
113:
114: } /* crcCompute() */
115:
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -