-
Notifications
You must be signed in to change notification settings - Fork 15
/
crc.hh
85 lines (77 loc) · 1.5 KB
/
crc.hh
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
Cyclic redundancy check
Copyright 2018 Ahmet Inan <[email protected]>
*/
#pragma once
namespace CODE {
template <typename TYPE>
class CRC
{
TYPE lut[256];
TYPE poly;
TYPE crc;
TYPE update(TYPE prev, bool data)
{
TYPE tmp = prev ^ data;
return (prev >> 1) ^ ((tmp & 1) * poly);
}
public:
CRC(TYPE poly, TYPE crc = 0) : poly(poly), crc(crc)
{
for (int j = 0; j < 256; ++j) {
TYPE tmp = j;
for (int i = 8; i; --i)
tmp = update(tmp, 0);
lut[j] = tmp;
}
}
void reset(TYPE v = 0)
{
crc = v;
}
TYPE operator()()
{
return crc;
}
TYPE operator()(bool data)
{
return crc = update(crc, data);
}
TYPE operator()(uint8_t data)
{
TYPE tmp = crc ^ data;
return crc = (crc >> 8) ^ lut[tmp & 255];
}
TYPE operator()(uint16_t data)
{
(*this)(uint8_t(data & 255));
(*this)(uint8_t((data >> 8) & 255));
return crc;
}
TYPE operator()(uint32_t data)
{
(*this)(uint8_t(data & 255));
(*this)(uint8_t((data >> 8) & 255));
(*this)(uint8_t((data >> 16) & 255));
(*this)(uint8_t((data >> 24) & 255));
return crc;
}
TYPE operator()(uint64_t data)
{
(*this)(uint8_t(data & 255));
(*this)(uint8_t((data >> 8) & 255));
(*this)(uint8_t((data >> 16) & 255));
(*this)(uint8_t((data >> 24) & 255));
(*this)(uint8_t((data >> 32) & 255));
(*this)(uint8_t((data >> 40) & 255));
(*this)(uint8_t((data >> 48) & 255));
(*this)(uint8_t((data >> 56) & 255));
return crc;
}
};
template<>
uint8_t CRC<uint8_t>::operator()(uint8_t data)
{
return crc = lut[crc ^ data];
}
}