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.

86 lines
2.5 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace JT809.Protocol
  5. {
  6. internal static class HexUtil
  7. {
  8. static readonly char[] HexdumpTable = new char[256 * 4];
  9. static HexUtil()
  10. {
  11. char[] digits = "0123456789ABCDEF".ToCharArray();
  12. for (int i = 0; i < 256; i++)
  13. {
  14. HexdumpTable[i << 1] = digits[(int)((uint)i >> 4 & 0x0F)];
  15. HexdumpTable[(i << 1) + 1] = digits[i & 0x0F];
  16. }
  17. }
  18. public static string DoHexDump(ReadOnlySpan<byte> buffer, int fromIndex, int length)
  19. {
  20. if (length == 0)
  21. {
  22. return "";
  23. }
  24. int endIndex = fromIndex + length;
  25. var buf = new char[length << 1];
  26. int srcIdx = fromIndex;
  27. int dstIdx = 0;
  28. for (; srcIdx < endIndex; srcIdx++, dstIdx += 2)
  29. {
  30. Array.Copy(HexdumpTable, buffer[srcIdx] << 1, buf, dstIdx, 2);
  31. }
  32. return new string(buf);
  33. }
  34. public static string DoHexDump(byte[] array, int fromIndex, int length)
  35. {
  36. if (length == 0)
  37. {
  38. return "";
  39. }
  40. int endIndex = fromIndex + length;
  41. var buf = new char[length << 1];
  42. int srcIdx = fromIndex;
  43. int dstIdx = 0;
  44. for (; srcIdx < endIndex; srcIdx++, dstIdx += 2)
  45. {
  46. Array.Copy(HexdumpTable, (array[srcIdx] & 0xFF) << 1, buf, dstIdx, 2);
  47. }
  48. return new string(buf);
  49. }
  50. }
  51. public static class CRCUtil
  52. {
  53. public static ulong[] CRC; //建立CRC16表
  54. private const ushort cnCRC_CCITT = 0x1021; //CRC校验多项式
  55. static CRCUtil()
  56. {
  57. InitCrcTable();
  58. }
  59. private static void InitCrcTable()
  60. {
  61. CRC = new ulong[256];
  62. ushort i, j;
  63. ushort nData;
  64. ushort nAccum;
  65. for (i = 0; i < 256; i++)
  66. {
  67. nData = (ushort)(i << 8);
  68. nAccum = 0;
  69. for (j = 0; j < 8; j++)
  70. {
  71. if (((nData ^ nAccum) & 0x8000) > 0)
  72. nAccum = (ushort)((nAccum << 1) ^ cnCRC_CCITT);
  73. else
  74. nAccum <<= 1;
  75. nData <<= 1;
  76. }
  77. CRC[i] = (ulong)nAccum;
  78. }
  79. }
  80. }
  81. }