HexUtils.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Text;
  3. namespace Ryujinx.Common
  4. {
  5. public static class HexUtils
  6. {
  7. private static readonly char[] HexChars = "0123456789ABCDEF".ToCharArray();
  8. private const int HexTableColumnWidth = 8;
  9. private const int HexTableColumnSpace = 3;
  10. // Modified for Ryujinx
  11. // Original by Pascal Ganaye - CPOL License
  12. // https://www.codeproject.com/Articles/36747/Quick-and-Dirty-HexDump-of-a-Byte-Array
  13. public static string HexTable(byte[] bytes, int bytesPerLine = 16)
  14. {
  15. if (bytes == null)
  16. {
  17. return "<null>";
  18. }
  19. int bytesLength = bytes.Length;
  20. int firstHexColumn =
  21. HexTableColumnWidth
  22. + HexTableColumnSpace;
  23. int firstCharColumn = firstHexColumn
  24. + bytesPerLine * HexTableColumnSpace
  25. + (bytesPerLine - 1) / HexTableColumnWidth
  26. + 2;
  27. int lineLength = firstCharColumn
  28. + bytesPerLine
  29. + Environment.NewLine.Length;
  30. char[] line = (new String(' ', lineLength - Environment.NewLine.Length) + Environment.NewLine).ToCharArray();
  31. int expectedLines = (bytesLength + bytesPerLine - 1) / bytesPerLine;
  32. StringBuilder result = new StringBuilder(expectedLines * lineLength);
  33. for (int i = 0; i < bytesLength; i += bytesPerLine)
  34. {
  35. line[0] = HexChars[(i >> 28) & 0xF];
  36. line[1] = HexChars[(i >> 24) & 0xF];
  37. line[2] = HexChars[(i >> 20) & 0xF];
  38. line[3] = HexChars[(i >> 16) & 0xF];
  39. line[4] = HexChars[(i >> 12) & 0xF];
  40. line[5] = HexChars[(i >> 8) & 0xF];
  41. line[6] = HexChars[(i >> 4) & 0xF];
  42. line[7] = HexChars[(i >> 0) & 0xF];
  43. int hexColumn = firstHexColumn;
  44. int charColumn = firstCharColumn;
  45. for (int j = 0; j < bytesPerLine; j++)
  46. {
  47. if (j > 0 && (j & 7) == 0)
  48. {
  49. hexColumn++;
  50. }
  51. if (i + j >= bytesLength)
  52. {
  53. line[hexColumn] = ' ';
  54. line[hexColumn + 1] = ' ';
  55. line[charColumn] = ' ';
  56. }
  57. else
  58. {
  59. byte b = bytes[i + j];
  60. line[hexColumn] = HexChars[(b >> 4) & 0xF];
  61. line[hexColumn + 1] = HexChars[b & 0xF];
  62. line[charColumn] = (b < 32 ? '·' : (char)b);
  63. }
  64. hexColumn += 3;
  65. charColumn++;
  66. }
  67. result.Append(line);
  68. }
  69. return result.ToString();
  70. }
  71. }
  72. }