Open FFBoard
Open source force feedback firmware
CRC.h
Go to the documentation of this file.
1/*
2 * CRC.h
3 *
4 * Created on: 10.01.2023
5 * Author: Yannick
6 */
7
8#ifndef SRC_CRC_H_
9#define SRC_CRC_H_
10#include "main.h"
11#include "array"
12
13
14template<typename T>
15T reverseBits(T value)
16{
17 static_assert(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4, "Type must be 1,2 or 4 bytes long");
18 value = ((value & 0xAAAAAAAA) >> 1) | ((value & 0x55555555) << 1);
19 value = ((value & 0xCCCCCCCC) >> 2) | ((value & 0x33333333) << 2);
20
21 if(sizeof(T)>1)
22 value = ((value & 0xF0F0F0F0) >> 4) | ((value & 0x0F0F0F0F) << 4);
23
24 if(sizeof(T)>3)
25 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
26
27 value = (value >> (4*sizeof(T))) | (value << (4*sizeof(T)));
28
29 return value; // & (1 << (sizeof(T)*8)) - 1
30}
31
35template<typename T,size_t LEN>
36void makeCrcTable(std::array<T,LEN> &table, const T crcpoly,const uint8_t bits,const bool refin = false,const bool refout = false)
37{
38 T mask = 1 << (bits-1);
39 for (uint16_t byte = 0; byte < LEN; ++byte)
40 {
41 uint8_t shiftin = std::max<int16_t>(bits-8,0);
42 T crc = (refin ? reverseBits<T>(byte) >> shiftin : byte);
43 for (uint8_t bit = 0; bit < bits; ++bit)
44 {
45 if (crc & mask)
46 {
47 crc = (crc << 1) ^ crcpoly;
48 }
49 else
50 {
51 crc <<= 1;
52 }
53 }
54 table[byte] = (refout ? reverseBits<T>(crc) : crc);
55 }
56}
57
58
59uint8_t calculateCrc8(std::array<uint8_t,256> &crctable,uint8_t* buf,uint16_t len,uint8_t crc=0);
60uint16_t calculateCrc16_8(std::array<uint16_t,256> &crctable,uint8_t* buf,uint16_t len,uint16_t crc=0);
61uint16_t calculateCrc16_8_rev(std::array<uint16_t,256> &crctable,uint8_t* buf,uint16_t len,uint16_t crc=0);
62
63#endif /* SRC_CRC_H_ */
void makeCrcTable(std::array< T, LEN > &table, const T crcpoly, const uint8_t bits, const bool refin=false, const bool refout=false)
Definition: CRC.h:36
uint16_t calculateCrc16_8_rev(std::array< uint16_t, 256 > &crctable, uint8_t *buf, uint16_t len, uint16_t crc=0)
Definition: CRC.cpp:33
uint8_t calculateCrc8(std::array< uint8_t, 256 > &crctable, uint8_t *buf, uint16_t len, uint8_t crc=0)
Definition: CRC.cpp:13
T reverseBits(T value)
Definition: CRC.h:15
uint16_t calculateCrc16_8(std::array< uint16_t, 256 > &crctable, uint8_t *buf, uint16_t len, uint16_t crc=0)
Definition: CRC.cpp:23
uint8_t crc