crc4.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * crc4.c - simple crc-4 calculations.
  3. *
  4. * This source code is licensed under the GNU General Public License, Version
  5. * 2. See the file COPYING for more details.
  6. */
  7. #include <linux/crc4.h>
  8. #include <linux/module.h>
  9. static const uint8_t crc4_tab[] = {
  10. 0x0, 0x7, 0xe, 0x9, 0xb, 0xc, 0x5, 0x2,
  11. 0x1, 0x6, 0xf, 0x8, 0xa, 0xd, 0x4, 0x3,
  12. };
  13. /**
  14. * crc4 - calculate the 4-bit crc of a value.
  15. * @crc: starting crc4
  16. * @x: value to checksum
  17. * @bits: number of bits in @x to checksum
  18. *
  19. * Returns the crc4 value of @x, using polynomial 0b10111.
  20. *
  21. * The @x value is treated as left-aligned, and bits above @bits are ignored
  22. * in the crc calculations.
  23. */
  24. uint8_t crc4(uint8_t c, uint64_t x, int bits)
  25. {
  26. int i;
  27. /* mask off anything above the top bit */
  28. x &= (1ull << bits) - 1;
  29. /* Align to 4-bits */
  30. bits = (bits + 3) & ~0x3;
  31. /* Calculate crc4 over four-bit nibbles, starting at the MSbit */
  32. for (i = bits - 4; i >= 0; i -= 4)
  33. c = crc4_tab[c ^ ((x >> i) & 0xf)];
  34. return c;
  35. }
  36. EXPORT_SYMBOL_GPL(crc4);
  37. MODULE_DESCRIPTION("CRC4 calculations");
  38. MODULE_LICENSE("GPL");