crc.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2019 Actions Semiconductor Co., Ltd
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. /**
  7. * @file crc interface
  8. */
  9. #include <stdint.h>
  10. #include <crc.h>
  11. uint16_t utils_crc16(const uint8_t *src, int len, uint16_t polynomial,
  12. uint16_t initial_value, int pad)
  13. {
  14. uint16_t crc = initial_value;
  15. int padding = (pad != 0) ? sizeof(crc) : 0;
  16. int i, b;
  17. /* src length + padding (if required) */
  18. for (i = 0; i < len + padding; i++) {
  19. for (b = 0; b < 8; b++) {
  20. uint16_t divide = crc & 0x8000;
  21. crc = (crc << 1);
  22. /* choose input bytes or implicit trailing zeros */
  23. if (i < len) {
  24. crc |= !!(src[i] & (0x80 >> b));
  25. }
  26. if (divide) {
  27. crc = crc ^ polynomial;
  28. }
  29. }
  30. }
  31. return crc;
  32. }
  33. static const uint32_t s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158,
  34. 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };
  35. // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/
  36. uint32_t utils_crc32(uint32_t crc, const uint8_t *ptr, int buf_len)
  37. {
  38. uint32_t crcu32 = crc;
  39. crcu32 = ~crcu32;
  40. while (buf_len--) {
  41. uint8_t b = *ptr++;
  42. crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];
  43. crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];
  44. }
  45. return ~crcu32;
  46. }