-
Notifications
You must be signed in to change notification settings - Fork 1
/
WireCrc.h
47 lines (46 loc) · 1.08 KB
/
WireCrc.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#ifndef WireCrc_h
#define WireCrc_h
#include <stdint.h>
class WireCrc {
public:
WireCrc() {}
/**
Starts a new CRC8 calculation.
@param data byte array
@param length number of bytes
@return uint8_t crc
*/
uint8_t calc(uint8_t *data, unsigned int length) {
seed = 0;
return update(data, length);
}
/**
Feed more data in the CRC calculation. calc() must
be called the first time, before using update()
multiple times.
@param data byte array
@param length number of bytes
@return uint8_t crc
*/
uint8_t update(uint8_t *data, unsigned int length) {
uint8_t crc = seed;
uint8_t extract;
uint8_t sum;
for (unsigned int i = 0; i < length; i++) {
extract = *data;
for (char j = 8; j; j--) {
sum = (crc ^ extract) & 0x01;
crc >>= 1;
if (sum) {
crc ^= 0x8C;
}
extract >>= 1;
}
data++;
}
return crc;
}
private:
uint8_t seed = 0;
};
#endif