Groonga 3.0.9 Source Code Document
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
crc.c
Go to the documentation of this file.
1 /*
2 ** crc.c - calculate CRC
3 **
4 ** See Copyright Notice in mruby.h
5 */
6 
7 #include <limits.h>
8 #include <stdint.h>
9 #include <stddef.h>
10 
11 // Calculate CRC (CRC-16-CCITT)
12 //
13 // 0000_0000_0000_0000_0000_0000_0000_0000
14 // ^|------- CRC -------|- work --|
15 // carry
16 #define CRC_16_CCITT 0x11021ul //x^16+x^12+x^5+1
17 #define CRC_XOR_PATTERN (CRC_16_CCITT << 8)
18 #define CRC_CARRY_BIT (0x01000000)
19 
20 uint16_t
21 calc_crc_16_ccitt(const uint8_t *src, size_t nbytes, uint16_t crc)
22 {
23  size_t ibyte;
24  uint32_t ibit;
25  uint32_t crcwk = crc << 8;
26 
27  for (ibyte = 0; ibyte < nbytes; ibyte++) {
28  crcwk |= *src++;
29  for (ibit = 0; ibit < CHAR_BIT; ibit++) {
30  crcwk <<= 1;
31  if (crcwk & CRC_CARRY_BIT) {
32  crcwk ^= CRC_XOR_PATTERN;
33  }
34  }
35  }
36  return (uint16_t)(crcwk >> 8);
37 }
38