-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathConstExpr_CRC.cpp
More file actions
69 lines (58 loc) · 1.9 KB
/
ConstExpr_CRC.cpp
File metadata and controls
69 lines (58 loc) · 1.9 KB
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
// =====================================================================================
// ConstExpr_CRC.cpp // Example from Fraunhofer-Institute for Integrated Circuits IIS
// =====================================================================================
/*
* Fraunhofer-Institute for Integrated Circuits IIS
* Am Wolfsmantel 33, 91058 Erlangen, Germany
* www.iis.fraunhofer.de
*
* Application Center Wireless Sensor Systems
* Sonntagsanger 1, 96450 Coburg, Germany
*
* Copyright Fraunhofer IIS, All rights reserved.
*/
module;
#include <cstdint> // for uint8_t
module modern_cpp:const_expr;
constexpr uint8_t MY_POLYNOM = 0x07;
constexpr int TABLE_SIZE = 256;
template<uint8_t POLYNOM>
constexpr auto crcTable{
[]() {
std::array<uint8_t, TABLE_SIZE> A {};
for (int i = 0; i < TABLE_SIZE; i++) {
A[i] = i;
for (int j = 0; j < 8; j++) {
if ((A[i] & 0x80) != 0) {
A[i] = (uint8_t)((A[i] << 1) ^ POLYNOM);
}
else {
A[i] <<= 1;
}
}
}
return A;
}()
};
constexpr auto tableBy10 = crcTable<10>;
constexpr auto tableBy20 = crcTable<20>;
static constexpr auto calcCRC(std::string_view data) {
uint8_t checksum{};
auto len{ data.size() };
for (std::size_t i{}; i != len; ++i) {
checksum = crcTable<MY_POLYNOM>[data[i] ^ checksum];
}
return checksum;
}
void main_constexpr_crc()
{
constexpr uint8_t checksum{ calcCRC("Hello World") };
std::println("Checksum is: {}", checksum);
// print table
for (std::size_t i{}; i != TABLE_SIZE; ++i) {
std::println("{:03}: {}", i, crcTable<MY_POLYNOM>[i]);
}
}
// =====================================================================================
// End-of-File
// =====================================================================================