crc.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved
  2. * See the LICENSE file for information about the license. */
  3. #include <stdint.h>
  4. #include <stddef.h>
  5. /* CRC8 with the specified initialization value 'init' and
  6. * polynomial 'poly'. */
  7. uint8_t crc8(const uint8_t *data, size_t len, uint8_t init, uint8_t poly)
  8. {
  9. uint8_t crc = init;
  10. size_t i, j;
  11. for (i = 0; i < len; i++) {
  12. crc ^= data[i];
  13. for (j = 0; j < 8; j++) {
  14. if ((crc & 0x80) != 0)
  15. crc = (uint8_t)((crc << 1) ^ poly);
  16. else
  17. crc <<= 1;
  18. }
  19. }
  20. return crc;
  21. }
  22. /* Sum all the specified bytes modulo 256.
  23. * Initialize the sum with 'init' (usually 0). */
  24. uint8_t sum_bytes(const uint8_t *data, size_t len, uint8_t init) {
  25. for (size_t i = 0; i < len; i++) init += data[i];
  26. return init;
  27. }
  28. /* Perform the bitwise xor of all the specified bytes.
  29. * Initialize xor value with 'init' (usually 0). */
  30. uint8_t xor_bytes(const uint8_t *data, size_t len, uint8_t init) {
  31. for (size_t i = 0; i < len; i++) init ^= data[i];
  32. return init;
  33. }