IQRF Gateway Daemon
crc.h
Go to the documentation of this file.
1 
17 #pragma once
18 
19 #include <cstdint>
20 
21 class Crc {
22 public:
23  static Crc& get()
24  {
25  static Crc crc;
26  return crc;
27  }
28 
29  uint16_t GetCRC_CCITT(uint8_t *buf, uint16_t len)
30  {
31  uint16_t crc_ccitt;
32  uint16_t i;
33 
34  //crc_tabccitt_init = false;
35  crc_ccitt = 0;
36 
37  for (i = 0; i < len; i++)
38  {
39  crc_ccitt = UpdateCRC_CCITT(crc_ccitt, buf[i]);
40  }
41 
42  return crc_ccitt;
43  }
44 
45 private:
46  Crc()
47  {
48  InitTabCRC_CCITT();
49  }
50 
51  /*******************************************************************\
52  * *
53  * uint16_t UpdateCRC_CCITT(uint16_t crc, uint8_t c); *
54  * *
55  * The function update_crc_ccitt calculates a new CRC-CCITT *
56  * value based on the previous value of the CRC and the next *
57  * byte of the data to be checked. *
58  * *
59  \*******************************************************************/
60 
61  uint16_t UpdateCRC_CCITT(uint16_t crc, uint8_t c)
62  {
63  uint16_t tmp, short_c;
64 
65  short_c = 0x00ff & (uint16_t)c;
66 
67  //if (!crc_tabccitt_init) InitTabCRC_CCITT();
68 
69  tmp = (crc >> 8) ^ short_c;
70  crc = (crc << 8) ^ crc_tabccitt[tmp];
71 
72  return crc;
73  }
74 
75  /*******************************************************************\
76  * *
77  * static void InitTabCRC_CCITT( void ); *
78  * *
79  * The function init_crcccitt_tab() is used to fill the array *
80  * for calculation of the CRC-CCITT with values. *
81  * *
82  \*******************************************************************/
83 
84  void InitTabCRC_CCITT()
85  {
86  int i, j;
87  uint16_t crc, c;
88 
89  for (i = 0; i < 256; i++)
90  {
91  crc = 0;
92  c = ((uint16_t)i) << 8;
93 
94  for (j = 0; j < 8; j++)
95  {
96  if ((crc ^ c) & 0x8000) crc = (crc << 1) ^ P_CCITT;
97  else crc = crc << 1;
98 
99  c = c << 1;
100  }
101 
102  crc_tabccitt[i] = crc;
103  }
104 
105  //crc_tabccitt_init = true;
106  }
107 
108  const uint16_t P_CCITT = 0x1021;
109 
110  //bool crc_tabccitt_init;
111  uint16_t crc_tabccitt[256];
112 
113 };
Definition: crc.h:21
uint16_t GetCRC_CCITT(uint8_t *buf, uint16_t len)
Definition: crc.h:29