BitStream
crc.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <array>
4 #include <cstdint>
5 
6 namespace bitstream::utility
7 {
8  inline constexpr auto CHECKSUM_TABLE = []()
9  {
10  constexpr uint32_t POLYNOMIAL = 0xEDB88320;
11 
12  std::array<uint32_t, 0x100> table{};
13 
14  for (uint32_t i = 0; i < 0x100; ++i)
15  {
16  uint32_t item = i;
17  for (uint32_t bit = 0; bit < 8; ++bit)
18  item = ((item & 1) != 0) ? (POLYNOMIAL ^ (item >> 1)) : (item >> 1);
19  table[i] = item;
20  }
21 
22  return table;
23  }();
24 
25  inline constexpr uint32_t crc_uint32(const uint8_t* bytes, uint32_t size)
26  {
27  uint32_t result = 0xFFFFFFFF;
28 
29  for (uint32_t i = 0; i < size; i++)
30  result = CHECKSUM_TABLE[(result & 0xFF) ^ *(bytes + i)] ^ (result >> 8);
31 
32  return ~result;
33  }
34 
35  inline constexpr uint32_t crc_uint32(const uint8_t* checksum, const uint8_t* bytes, uint32_t size)
36  {
37  uint32_t result = 0xFFFFFFFF;
38 
39  for (uint32_t i = 0; i < 4; i++)
40  result = CHECKSUM_TABLE[(result & 0xFF) ^ *(checksum + i)] ^ (result >> 8);
41 
42  for (uint32_t i = 0; i < size; i++)
43  result = CHECKSUM_TABLE[(result & 0xFF) ^ *(bytes + i)] ^ (result >> 8);
44 
45  return ~result;
46  }
47 }
Definition: bits.h:7
constexpr auto CHECKSUM_TABLE
Definition: crc.h:8
constexpr uint32_t crc_uint32(const uint8_t *bytes, uint32_t size)
Definition: crc.h:25