crc32.c 928 B

1234567891011121314151617181920212223242526272829
  1. /* Simple public domain implementation of the standard CRC32 checksum.
  2. * Outputs the checksum for each file given as a command line argument.
  3. * Invalid file names and files that cause errors are silently skipped.
  4. * The program reads from stdin if it is called with no arguments. */
  5. #include <stdio.h>
  6. #include <stdint.h>
  7. #include <stdlib.h>
  8. static uint32_t crc32_for_byte(uint32_t r) {
  9. for(int j = 0; j < 8; ++j)
  10. r = (r & 1? 0: (uint32_t)0xEDB88320L) ^ r >> 1;
  11. return r ^ (uint32_t)0xFF000000L;
  12. }
  13. void crc32(const void *data, uint32_t n_bytes, uint32_t* crc) {
  14. static uint32_t table[0x100];
  15. if(!*table)
  16. for(uint32_t i = 0; i < 0x100; ++i)
  17. table[i] = crc32_for_byte(i);
  18. for(uint32_t i = 0; i < n_bytes; ++i)
  19. *crc = table[(uint8_t)*crc ^ ((uint8_t*)data)[i]] ^ *crc >> 8;
  20. }
  21. uint32_t crc32_buf(const void *buf, uint32_t n_bytes) {
  22. uint32_t crc = 0;
  23. crc32(buf, n_bytes, &crc);
  24. return crc;
  25. }