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.

54 lines
1.2 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Apewer.Internals
  5. {
  6. class CRC16
  7. {
  8. public static CRC16 Instance = new CRC16();
  9. const ushort origin = 0xFFFF;
  10. const ushort polynomial = 0xA001;
  11. ushort[] table = new ushort[256];
  12. public CRC16()
  13. {
  14. ushort value, temp;
  15. for (ushort i = 0; i < table.Length; ++i)
  16. {
  17. value = 0;
  18. temp = i;
  19. for (byte j = 0; j < 8; ++j)
  20. {
  21. if (((value ^ temp) & 0x0001) != 0)
  22. {
  23. value = (ushort)((value >> 1) ^ polynomial);
  24. }
  25. else
  26. {
  27. value >>= 1;
  28. }
  29. temp >>= 1;
  30. }
  31. table[i] = value;
  32. }
  33. }
  34. public ushort Compute(byte[] bytes)
  35. {
  36. ushort crc = origin;
  37. for (int i = 0; i < bytes.Length; ++i)
  38. {
  39. byte index = (byte)(crc ^ bytes[i]);
  40. crc = (ushort)((crc >> 8) ^ table[index]);
  41. }
  42. return crc;
  43. }
  44. }
  45. }