blob: cbc649662282c2c37bdfbd735c0adf6774b68319 [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001/*
2 * Computes the CRC for transmitted and received data using
3 * the CCITT 16bit algorithm (X^16 + X^12 + X^5 + 1) with
4 * a 0xFFFF initialization vector.
5 */
6
7#define CRC16_INIT_VALUE 0xFFFF
8
9 /*
10 * Computes an updated version of the CRC from existing CRC.
11 * crc: the previous values of the CRC
12 * buf: the data on which to apply the checksum
13 * length: the number of bytes of data in 'buf' to be calculated.
14 */
15unsigned short update_crc16(unsigned short crc, const unsigned char *buf,
16 unsigned int length)
17{
18 unsigned int i;
19 for (i = 0; i < length; i++) {
20 crc = (unsigned char) (crc >> 8) | (crc << 8);
21 crc ^= buf[i];
22 crc ^= (unsigned char) (crc & 0xff) >> 4;
23 crc ^= (crc << 8) << 4;
24 crc ^= ((crc & 0xff) << 4) << 1;
25 }
26 return crc;
27}
28
29 /*
30 * Computes a CRC, starting with an initialization value.
31 * buf: the data on which to apply the checksum
32 * length: the number of bytes of data in 'buf' to be calculated.
33 */
34unsigned short crc16(const unsigned char *buf, unsigned int length)
35{
36 unsigned short crc = CRC16_INIT_VALUE;
37 return update_crc16(crc, buf, length);
38}