-
Notifications
You must be signed in to change notification settings - Fork 4
/
Crc16.cpp
60 lines (48 loc) · 1.35 KB
/
Crc16.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
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
#include "Crc16.h"
#include "CrcParameters.h"
#include <iostream>
#include <iomanip>
#include <cstdint>
#include <array>
//*****************************************************************************
void Crc16::DisplayTable() const
{
int index = 0;
for (int i = 0; i < 16; ++i)
{
for (int j = 0; j < 16; ++j)
{
std::cout << "0x" << std::uppercase << std::hex << std::setfill('0') << std::setw(4) << crcTable[index++] << ", ";
}
std::cout << "\n";
}
}
//*****************************************************************************
void Crc16::GenerateTable(uint16_t polynomial, bool reflectIn, bool reflectOut)
{
for (int byte = 0; byte < 256; ++byte)
{
uint16_t crc = (reflectIn ? (Reverse(uint16_t(byte)) >> 8) : byte);
for (int bit = 16; bit > 0; --bit)
{
if (crc & 0x8000)
{
crc = (crc << 1) ^ polynomial;
}
else
{
crc <<= 1;
}
}
crcTable[byte] = (reflectOut ? Reverse(crc) : crc);
}
}
//*****************************************************************************
uint16_t Crc16::Reverse(uint16_t value) const
{
value = ((value & 0xAAAA) >> 1) | ((value & 0x5555) << 1);
value = ((value & 0xCCCC) >> 2) | ((value & 0x3333) << 2);
value = ((value & 0xF0F0) >> 4) | ((value & 0x0F0F) << 4);
value = (value >> 8) | (value << 8);
return value;
}