crc.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <flate.h>
  12. uint32_t*
  13. mkcrctab(uint32_t poly)
  14. {
  15. uint32_t *crctab;
  16. uint32_t crc;
  17. int i, j;
  18. crctab = malloc(256 * sizeof(uint32_t));
  19. if(crctab == nil)
  20. return nil;
  21. for(i = 0; i < 256; i++){
  22. crc = i;
  23. for(j = 0; j < 8; j++){
  24. if(crc & 1)
  25. crc = (crc >> 1) ^ poly;
  26. else
  27. crc >>= 1;
  28. }
  29. crctab[i] = crc;
  30. }
  31. return crctab;
  32. }
  33. uint32_t
  34. blockcrc(uint32_t *crctab, uint32_t crc, void *vbuf, int n)
  35. {
  36. uint8_t *buf, *ebuf;
  37. crc ^= 0xffffffff;
  38. buf = vbuf;
  39. ebuf = buf + n;
  40. while(buf < ebuf)
  41. crc = crctab[(crc & 0xff) ^ *buf++] ^ (crc >> 8);
  42. return crc ^ 0xffffffff;
  43. }