CRC16.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. namespace AmrControl.Common
  2. {
  3. public class CRCHelper
  4. {
  5. #region CRC16
  6. public static byte[] CRC16(byte[] data)
  7. {
  8. int len = data.Length;
  9. if (len > 0)
  10. {
  11. ushort crc = 0xFFFF;
  12. for (int i = 0; i < len; i++)
  13. {
  14. crc = (ushort)(crc ^ (data[i]));
  15. for (int j = 0; j < 8; j++)
  16. {
  17. crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
  18. }
  19. }
  20. byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
  21. byte lo = (byte)(crc & 0x00FF); //低位置
  22. return new byte[] { hi, lo };
  23. }
  24. return new byte[] { 0, 0 };
  25. }
  26. public static byte[] CRC16(byte[] data, int startIndex, int len)
  27. {
  28. if (len > 0 && data != null)
  29. {
  30. ushort crc = 0xFFFF;
  31. for (int i = startIndex; i < startIndex + len && i < data.Length; i++)
  32. {
  33. crc = (ushort)(crc ^ (data[i]));
  34. for (int j = 0; j < 8; j++)
  35. {
  36. crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
  37. }
  38. }
  39. byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
  40. byte lo = (byte)(crc & 0x00FF); //低位置
  41. return new byte[] { hi, lo };
  42. }
  43. return new byte[] { 0, 0 };
  44. }
  45. #endregion
  46. }
  47. }