small crc32 calculator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

crc32.c 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. enum { CRC_TABLE_SIZE = 0x100 };
  2. static inline uint32_t
  3. crc_reflect(uint32_t input)
  4. {
  5. uint32_t reflected = 0;
  6. for (int i = 0; i < 32; i++) {
  7. reflected <<= 1;
  8. reflected |= input & 1;
  9. input >>= 1;
  10. }
  11. return reflected;
  12. }
  13. static inline void
  14. crc_be_fill_table(uint32_t *table, uint32_t polynomial)
  15. {
  16. const uint32_t lsb = 1 << 31;
  17. uint32_t poly = polynomial;
  18. for (int c = 0; c < CRC_TABLE_SIZE; c++) {
  19. uint32_t v = c << 24;
  20. for (int i = 0; i < 8; i++) {
  21. if (v & lsb) {
  22. v <<= 1;
  23. v ^= poly;
  24. } else {
  25. v <<= 1;
  26. }
  27. }
  28. *table++ = v;
  29. }
  30. }
  31. static inline void
  32. crc_le_fill_table(uint32_t *table, uint32_t polynomial)
  33. {
  34. const uint32_t lsb = 1;
  35. uint32_t poly = crc_reflect(polynomial);
  36. for (int c = 0; c < CRC_TABLE_SIZE; c++) {
  37. uint32_t v = c;
  38. for (int i = 0; i < 8; i++) {
  39. if (v & lsb) {
  40. v >>= 1;
  41. v ^= poly;
  42. } else {
  43. v >>= 1;
  44. }
  45. }
  46. *table++ = v;
  47. }
  48. }
  49. static inline void
  50. crc_be_cycle(uint32_t *table, uint32_t *remainder, uint8_t c)
  51. {
  52. const uint8_t i = (*remainder >> 24) ^ c;
  53. *remainder = (*remainder << 8) ^ table[i];
  54. }
  55. static inline void
  56. crc_le_cycle(uint32_t *table, uint32_t *remainder, uint8_t c)
  57. {
  58. const uint8_t i = (*remainder & 0xFF) ^ c;
  59. *remainder = (*remainder >> 8) ^ table[i];
  60. }