crc32.c 1013 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define CRC32_POLY 0x04C11DB7L
  4. unsigned int get_sum_poly(unsigned char top_byte)
  5. {
  6. /// sum all the polys at various offsets
  7. unsigned int sum_poly = top_byte << 24;
  8. int i;
  9. for (i = 0; i < 8; ++i) {
  10. /// check the top bit
  11. if( ( sum_poly >> 31 ) != 0 )
  12. /// TODO : understand why '<<' first
  13. sum_poly = ( sum_poly << 1 ) ^ CRC32_POLY;
  14. else
  15. sum_poly <<= 1;
  16. }
  17. return sum_poly;
  18. }
  19. void create_table(unsigned int *table)
  20. {
  21. for( int i = 0; i < 256; ++ i )
  22. {
  23. table[i] = get_sum_poly( (unsigned char) i );
  24. }
  25. }
  26. static const unsigned int *crc32_table = NULL;
  27. unsigned int
  28. xcrc32(const unsigned char *buf, int len, unsigned int init)
  29. {
  30. unsigned int crc = init;
  31. static unsigned int table[256];
  32. if (!crc32_table) {
  33. create_table(table);
  34. crc32_table = &table[0];
  35. }
  36. while (len--)
  37. {
  38. crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
  39. buf++;
  40. }
  41. return crc;
  42. }