Advertisement
Guest User

Untitled

a guest
Jun 20th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. #include <string>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. uint16_t crcAdd(uint8_t c) {
  7. int crc = 0;
  8.  
  9. for (int j = 0; j < 8; j++) {
  10. if ( (crc ^ c) & 0x0001 ) {
  11. crc = (crc >> 1) ^ 0xA001;
  12. } else {
  13. crc = crc >> 1;
  14. }
  15.  
  16. c = c >> 1;
  17. }
  18. return crc;
  19. }
  20.  
  21. uint16_t update_crc_16( uint16_t crc, unsigned char c ) {
  22. return (crc >> 8) ^ crcAdd((crc ^ (uint16_t) c) & 0x00FF);
  23. }
  24.  
  25. class Reliable {
  26. public:
  27. uint16_t getCrc() {
  28. return crc;
  29. }
  30.  
  31. uint16_t* getCrcAddr() {
  32. return &crc;
  33. }
  34.  
  35. protected:
  36. virtual uint16_t calculateCrc() = 0;
  37.  
  38. void updateCrc(int crc) {
  39. this->crc = crc;
  40. }
  41.  
  42. void assertCorrectCrc() {
  43. assert(calculateCrc() == getCrc());
  44. }
  45.  
  46. private:
  47. uint16_t crc;
  48. };
  49.  
  50. class ReliableInt: public Reliable {
  51. public:
  52. ReliableInt(int value) : value(value) {
  53. updateCrc(calculateCrc());
  54. }
  55.  
  56. ReliableInt operator + (ReliableInt other) {
  57. this->assertCorrectCrc();
  58. other.assertCorrectCrc();
  59. return ReliableInt(value + other.value);
  60. }
  61.  
  62. ReliableInt operator - (ReliableInt other) {
  63. this->assertCorrectCrc();
  64. other.assertCorrectCrc();
  65. return ReliableInt(value - other.value);
  66. }
  67.  
  68. private:
  69. uint16_t calculateCrc() override {
  70. uint16_t crc = 0;
  71. int copyval = value;
  72. for (int i = 0; i < 4; i++) {
  73. crc = update_crc_16(crc, (uint8_t)copyval & 0xFF);
  74. copyval >>= 4;
  75. }
  76. return crc;
  77. }
  78.  
  79. int value;
  80. };
  81.  
  82. class ReliableString: public Reliable {
  83. public:
  84. ReliableString(const string& value) : value(value) {
  85. updateCrc(calculateCrc());
  86. }
  87. private:
  88. uint16_t calculateCrc() override {
  89. uint16_t crc = 0;
  90. for (char c : value) {
  91. crc = update_crc_16(crc, (uint8_t)c);
  92. }
  93. return crc;
  94. }
  95.  
  96. string value;
  97. };
  98.  
  99. int main() {
  100. ReliableInt a(5);
  101. ReliableInt b(10);
  102.  
  103. cout << a.getCrc() << ' ' << b.getCrc() << endl;
  104. cout << (a + b).getCrc() << endl;
  105.  
  106. // Destroy CRC value of A
  107. uint16_t* addr = a.getCrcAddr();
  108. ++(*addr);
  109.  
  110. cout << (a + b).getCrc() << endl;
  111.  
  112. return 0;
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement