crc.c 631 B

1234567891011121314151617181920212223
  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. }