CRC-CCITT (0xFFFF).cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Runtime.Remoting.Metadata.W3cXsd2001;
  5. namespace CrcTest
  6. {
  7. /// <summary>
  8. /// SCBC通讯协议CRC校验位生成
  9. /// </summary>
  10. class Program
  11. {
  12. public static string CalcCRC16(byte[] data)
  13. {
  14. ushort crc = 0xFFFF;
  15. //byte[] data = GetBytesFromHexString(strInput);
  16. for (int i = 0; i < data.Length; i++)
  17. {
  18. crc ^= (ushort)(data[i] << 8);
  19. for (int j = 0; j < 8; j++)
  20. {
  21. if ((crc & 0x8000) > 0)
  22. crc = (ushort)((crc << 1) ^ 0x1021);
  23. else
  24. crc <<= 1;
  25. }
  26. }
  27. return crc.ToString("X4");
  28. }
  29. public Byte[] GetBytesFromHexString(string strInput)
  30. {
  31. Byte[] bytArOutput = new Byte[] { };
  32. if (!string.IsNullOrEmpty(strInput) && strInput.Length % 2 == 0)
  33. {
  34. SoapHexBinary hexBinary = null;
  35. hexBinary = SoapHexBinary.Parse(strInput);
  36. if (hexBinary != null)
  37. {
  38. bytArOutput = hexBinary.Value;
  39. }
  40. }
  41. return bytArOutput;
  42. }
  43. }
  44. }