CRCUtils.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections;
  3. using System.Text;
  4. namespace WHC.OrderWater.Commons
  5. {
  6. /// <summary>
  7. /// CRCУÑ鸨ÖúÀà
  8. /// </summary>
  9. public sealed class CrcUtils
  10. {
  11. private static ushort[] CRC16Table = null;
  12. private static uint[] CRC32Table = null;
  13. private static void MakeCRC16Table()
  14. {
  15. if (CRC16Table != null) return;
  16. CRC16Table = new ushort[256];
  17. for (ushort i = 0; i < 256; i++)
  18. {
  19. ushort vCRC = i;
  20. for (int j = 0; j < 8; j++)
  21. if (vCRC % 2 == 0)
  22. vCRC = (ushort)(vCRC >> 1);
  23. else vCRC = (ushort)((vCRC >> 1) ^ 0x8408);
  24. CRC16Table[i] = vCRC;
  25. }
  26. }
  27. private static void MakeCRC32Table()
  28. {
  29. if (CRC32Table != null) return;
  30. CRC32Table = new uint[256];
  31. for (uint i = 0; i < 256; i++)
  32. {
  33. uint vCRC = i;
  34. for (int j = 0; j < 8; j++)
  35. if (vCRC % 2 == 0)
  36. vCRC = (uint)(vCRC >> 1);
  37. else vCRC = (uint)((vCRC >> 1) ^ 0xEDB88320);
  38. CRC32Table[i] = vCRC;
  39. }
  40. }
  41. private static ushort UpdateCRC16(byte AByte, ushort ASeed)
  42. {
  43. return (ushort)(CRC16Table[(ASeed & 0x000000FF) ^ AByte] ^ (ASeed >> 8));
  44. }
  45. private static uint UpdateCRC32(byte AByte, uint ASeed)
  46. {
  47. return (uint)(CRC32Table[(ASeed & 0x000000FF) ^ AByte] ^ (ASeed >> 8));
  48. }
  49. public static ushort CRC16(byte[] ABytes)
  50. {
  51. MakeCRC16Table();
  52. ushort Result = 0xFFFF;
  53. foreach (byte vByte in ABytes)
  54. Result = UpdateCRC16(vByte, Result);
  55. return (ushort)(~Result);
  56. }
  57. public static ushort CRC16(string AString, Encoding AEncoding)
  58. {
  59. return CRC16(AEncoding.GetBytes(AString));
  60. }
  61. public static ushort CRC16(string AString)
  62. {
  63. return CRC16(AString, Encoding.UTF8);
  64. }
  65. public static uint CRC32(byte[] ABytes)
  66. {
  67. MakeCRC32Table();
  68. uint Result = 0xFFFFFFFF;
  69. foreach (byte vByte in ABytes)
  70. Result = UpdateCRC32(vByte, Result);
  71. return (uint)(~Result);
  72. }
  73. public static uint CRC32(string AString, Encoding AEncoding)
  74. {
  75. return CRC32(AEncoding.GetBytes(AString));
  76. }
  77. public static uint CRC32(string AString)
  78. {
  79. return CRC32(AString, Encoding.UTF8);
  80. }
  81. }
  82. }