Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <iostream>
- using namespace std;
- uint16_t crcAdd(uint8_t c) {
- int crc = 0;
- for (int j = 0; j < 8; j++) {
- if ( (crc ^ c) & 0x0001 ) {
- crc = (crc >> 1) ^ 0xA001;
- } else {
- crc = crc >> 1;
- }
- c = c >> 1;
- }
- return crc;
- }
- uint16_t update_crc_16( uint16_t crc, unsigned char c ) {
- return (crc >> 8) ^ crcAdd((crc ^ (uint16_t) c) & 0x00FF);
- }
- class Reliable {
- public:
- uint16_t getCrc() {
- return crc;
- }
- uint16_t* getCrcAddr() {
- return &crc;
- }
- protected:
- virtual uint16_t calculateCrc() = 0;
- void updateCrc(int crc) {
- this->crc = crc;
- }
- void assertCorrectCrc() {
- assert(calculateCrc() == getCrc());
- }
- private:
- uint16_t crc;
- };
- class ReliableInt: public Reliable {
- public:
- ReliableInt(int value) : value(value) {
- updateCrc(calculateCrc());
- }
- ReliableInt operator + (ReliableInt other) {
- this->assertCorrectCrc();
- other.assertCorrectCrc();
- return ReliableInt(value + other.value);
- }
- ReliableInt operator - (ReliableInt other) {
- this->assertCorrectCrc();
- other.assertCorrectCrc();
- return ReliableInt(value - other.value);
- }
- private:
- uint16_t calculateCrc() override {
- uint16_t crc = 0;
- int copyval = value;
- for (int i = 0; i < 4; i++) {
- crc = update_crc_16(crc, (uint8_t)copyval & 0xFF);
- copyval >>= 4;
- }
- return crc;
- }
- int value;
- };
- class ReliableString: public Reliable {
- public:
- ReliableString(const string& value) : value(value) {
- updateCrc(calculateCrc());
- }
- private:
- uint16_t calculateCrc() override {
- uint16_t crc = 0;
- for (char c : value) {
- crc = update_crc_16(crc, (uint8_t)c);
- }
- return crc;
- }
- string value;
- };
- int main() {
- ReliableInt a(5);
- ReliableInt b(10);
- cout << a.getCrc() << ' ' << b.getCrc() << endl;
- cout << (a + b).getCrc() << endl;
- // Destroy CRC value of A
- uint16_t* addr = a.getCrcAddr();
- ++(*addr);
- cout << (a + b).getCrc() << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement