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.
 
 
 

81 line
2.5 KiB

  1. using System;
  2. namespace JT1078.DotNetty.TestHosting
  3. {
  4. public static partial class BinaryExtensions
  5. {
  6. public static string ToHexString(this byte[] source)
  7. {
  8. return HexUtil.DoHexDump(source, 0, source.Length).ToUpper();
  9. }
  10. /// <summary>
  11. /// 16进制字符串转16进制数组
  12. /// </summary>
  13. /// <param name="hexString"></param>
  14. /// <param name="separator"></param>
  15. /// <returns></returns>
  16. public static byte[] ToHexBytes(this string hexString)
  17. {
  18. hexString = hexString.Replace(" ", "");
  19. byte[] buf = new byte[hexString.Length / 2];
  20. ReadOnlySpan<char> readOnlySpan = hexString.AsSpan();
  21. for (int i = 0; i < hexString.Length; i++)
  22. {
  23. if (i % 2 == 0)
  24. {
  25. buf[i / 2] = Convert.ToByte(readOnlySpan.Slice(i, 2).ToString(), 16);
  26. }
  27. }
  28. return buf;
  29. }
  30. }
  31. public static class HexUtil
  32. {
  33. static readonly char[] HexdumpTable = new char[256 * 4];
  34. static HexUtil()
  35. {
  36. char[] digits = "0123456789ABCDEF".ToCharArray();
  37. for (int i = 0; i < 256; i++)
  38. {
  39. HexdumpTable[i << 1] = digits[(int)((uint)i >> 4 & 0x0F)];
  40. HexdumpTable[(i << 1) + 1] = digits[i & 0x0F];
  41. }
  42. }
  43. public static string DoHexDump(ReadOnlySpan<byte> buffer, int fromIndex, int length)
  44. {
  45. if (length == 0)
  46. {
  47. return "";
  48. }
  49. int endIndex = fromIndex + length;
  50. var buf = new char[length << 1];
  51. int srcIdx = fromIndex;
  52. int dstIdx = 0;
  53. for (; srcIdx < endIndex; srcIdx++, dstIdx += 2)
  54. {
  55. Array.Copy(HexdumpTable, buffer[srcIdx] << 1, buf, dstIdx, 2);
  56. }
  57. return new string(buf);
  58. }
  59. public static string DoHexDump(byte[] array, int fromIndex, int length)
  60. {
  61. if (length == 0)
  62. {
  63. return "";
  64. }
  65. int endIndex = fromIndex + length;
  66. var buf = new char[length << 1];
  67. int srcIdx = fromIndex;
  68. int dstIdx = 0;
  69. for (; srcIdx < endIndex; srcIdx++, dstIdx += 2)
  70. {
  71. Array.Copy(HexdumpTable, (array[srcIdx] & 0xFF) << 1, buf, dstIdx, 2);
  72. }
  73. return new string(buf);
  74. }
  75. }
  76. }