mmu2_crc.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /// @file
  2. #pragma once
  3. #include <stdint.h>
  4. namespace modules {
  5. /// Contains all the necessary functions for computation of CRC
  6. namespace crc {
  7. class CRC8 {
  8. public:
  9. /// Compute/update CRC8 CCIIT from 8bits.
  10. /// Details: https://www.nongnu.org/avr-libc/user-manual/group__util__crc.html
  11. static uint8_t CCITT_update(uint8_t crc, uint8_t b);
  12. static constexpr uint8_t CCITT_updateCX(uint8_t crc, uint8_t b) {
  13. uint8_t data = crc ^ b;
  14. for (uint8_t i = 0; i < 8; i++) {
  15. if ((data & 0x80U) != 0) {
  16. data <<= 1U;
  17. data ^= 0x07U;
  18. } else {
  19. data <<= 1U;
  20. }
  21. }
  22. return data;
  23. }
  24. /// Compute/update CRC8 CCIIT from 16bits (convenience wrapper)
  25. static constexpr uint8_t CCITT_updateW(uint8_t crc, uint16_t w) {
  26. union U {
  27. uint8_t b[2];
  28. uint16_t w;
  29. explicit constexpr inline U(uint16_t w)
  30. : w(w) {}
  31. } u(w);
  32. return CCITT_updateCX(CCITT_updateCX(crc, u.b[0]), u.b[1]);
  33. }
  34. };
  35. } // namespace crc
  36. } // namespace modules