2016-09-18 22:33:26 +00:00
|
|
|
//
|
|
|
|
// CRC.hpp
|
|
|
|
// Clock Signal
|
|
|
|
//
|
|
|
|
// Created by Thomas Harte on 18/09/2016.
|
|
|
|
// Copyright © 2016 Thomas Harte. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
#ifndef CRC_hpp
|
|
|
|
#define CRC_hpp
|
|
|
|
|
|
|
|
#include <cstdint>
|
|
|
|
|
|
|
|
namespace NumberTheory {
|
|
|
|
|
2017-07-22 21:39:51 +00:00
|
|
|
/*! Provides a class capable of accumulating a CRC16 from source data. */
|
2016-09-18 22:33:26 +00:00
|
|
|
class CRC16 {
|
|
|
|
public:
|
2017-07-22 21:39:51 +00:00
|
|
|
/*!
|
|
|
|
Instantiates a CRC16 that will compute the CRC16 specified by the supplied
|
|
|
|
@c polynomial and @c reset_value.
|
|
|
|
*/
|
2016-09-18 22:33:26 +00:00
|
|
|
CRC16(uint16_t polynomial, uint16_t reset_value) :
|
2017-03-26 18:34:47 +00:00
|
|
|
reset_value_(reset_value), value_(reset_value) {
|
|
|
|
for(int c = 0; c < 256; c++) {
|
2016-12-31 19:15:20 +00:00
|
|
|
uint16_t shift_value = (uint16_t)(c << 8);
|
2017-03-26 18:34:47 +00:00
|
|
|
for(int b = 0; b < 8; b++) {
|
2016-12-31 19:15:20 +00:00
|
|
|
uint16_t exclusive_or = (shift_value&0x8000) ? polynomial : 0x0000;
|
|
|
|
shift_value = (uint16_t)(shift_value << 1) ^ exclusive_or;
|
|
|
|
}
|
|
|
|
xor_table[c] = (uint16_t)shift_value;
|
2016-09-18 22:33:26 +00:00
|
|
|
}
|
|
|
|
}
|
2016-12-31 19:15:20 +00:00
|
|
|
|
2017-07-22 21:39:51 +00:00
|
|
|
/// Resets the CRC to the reset value.
|
2016-12-31 19:15:20 +00:00
|
|
|
inline void reset() { value_ = reset_value_; }
|
2017-07-22 21:39:51 +00:00
|
|
|
|
|
|
|
/// Updates the CRC to include @c byte.
|
2016-12-31 19:15:20 +00:00
|
|
|
inline void add(uint8_t byte) {
|
|
|
|
value_ = (uint16_t)((value_ << 8) ^ xor_table[(value_ >> 8) ^ byte]);
|
|
|
|
}
|
2017-07-22 21:39:51 +00:00
|
|
|
|
|
|
|
/// @returns The current value of the CRC.
|
2016-12-28 00:03:46 +00:00
|
|
|
inline uint16_t get_value() const { return value_; }
|
2017-07-22 21:39:51 +00:00
|
|
|
|
|
|
|
/// Sets the current value of the CRC.
|
2016-12-28 23:29:37 +00:00
|
|
|
inline void set_value(uint16_t value) { value_ = value; }
|
2016-09-18 22:33:26 +00:00
|
|
|
|
|
|
|
private:
|
2016-12-31 19:15:20 +00:00
|
|
|
const uint16_t reset_value_;
|
|
|
|
uint16_t xor_table[256];
|
2016-09-18 22:33:26 +00:00
|
|
|
uint16_t value_;
|
|
|
|
};
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif /* CRC_hpp */
|