blob: b770f377bed974366472b2ca1959bc0d7f2cfd87 [file] [log] [blame]
Brian Silverman8cbf8332013-12-11 13:59:42 -08001#include "bbb/crc.h"
2
3#include "aos/common/once.h"
4
5// There are various implementations that look a lot like this scattered around
6// the internet.
7
8namespace cape {
9namespace {
10
11const uint32_t kPolynomial = 0x04c11db7;
12
13const uint32_t *GenerateTable() {
14 static uint32_t table[256];
15
16 for (int i = 0; i < 256; ++i) {
17 uint32_t c = i << 24;
18 for (int j = 8; j > 0; --j) {
19 c = c & 0x80000000 ? ((c << 1) ^ kPolynomial) : (c << 1);
20 }
21 table[i] = c;
22 }
23
24 return table;
25}
26
27} // namespace
28
29uint32_t CalculateChecksum(uint8_t *data, size_t length) {
30 static ::aos::once<const uint32_t> table_once(GenerateTable);
31 const uint32_t *const table = table_once.Get();
32
33 uint32_t r = 0xFFFFFFFF;
34
35 for (size_t i = 0; i < length; ++i) {
36 r = (r << 8) ^ table[(r >> 24) ^ data[i]];
37 }
38
39 return ~r;
40}
41
42} // namespace cape