-
Notifications
You must be signed in to change notification settings - Fork 0
/
crc.cpp
33 lines (25 loc) · 816 Bytes
/
crc.cpp
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
/*
* The width of the CRC calculation and result.
* Modify the typedef for a 16 or 32-bit CRC standard.
*/
typedef uint8_t crc;
#define WIDTH (8 * sizeof(crc))
#define TOPBIT (1 << (WIDTH - 1))
crc crcSlow(uint8_t const message[], int nBytes) {
crc remainder = 0;
// Perform modulo-2 division, a byte at a time.
for (int byte = 0; byte < nBytes; ++byte) {
// Bring the next byte into the remainder.
remainder ^= (message[byte] << (WIDTH - 8));
// Perform modulo-2 division, a bit at a time.
for (uint8_t bit = 8; bit > 0; --bit) {
// Try to divide the current data bit.
if (remainder & TOPBIT)
remainder = (remainder << 1) ^ POLYNOMIAL;
else
remainder = (remainder << 1);
}
}
// The final remainder is the CRC result.
return (remainder);
}