crc.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  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. uint8_t crc = init;
  9. size_t i, j;
  10. for(i = 0; i < len; i++) {
  11. crc ^= data[i];
  12. for(j = 0; j < 8; j++) {
  13. if((crc & 0x80) != 0)
  14. crc = (uint8_t)((crc << 1) ^ poly);
  15. else
  16. crc <<= 1;
  17. }
  18. }
  19. return crc;
  20. }
  21. /* Sum all the specified bytes modulo 256.
  22. * Initialize the sum with 'init' (usually 0). */
  23. uint8_t sum_bytes(const uint8_t* data, size_t len, uint8_t init) {
  24. for(size_t i = 0; i < len; i++) init += data[i];
  25. return init;
  26. }
  27. /* Perform the bitwise xor of all the specified bytes.
  28. * Initialize xor value with 'init' (usually 0). */
  29. uint8_t xor_bytes(const uint8_t* data, size_t len, uint8_t init) {
  30. for(size_t i = 0; i < len; i++) init ^= data[i];
  31. return init;
  32. }