Guest User

Untitled

a guest
Jul 16th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1.  
  2. public static string HexDump(byte[] bytes, int bytesLength, int bytesPerLine = 16)
  3. {
  4. if (bytes == null) return "<null>";
  5. //int bytesLength = bytes.Length;
  6.  
  7. char[] HexChars = "0123456789ABCDEF".ToCharArray();
  8.  
  9. int firstHexColumn =
  10. 8 // 8 characters for the address
  11. + 3; // 3 spaces
  12.  
  13. int firstCharColumn = firstHexColumn
  14. + bytesPerLine * 3 // - 2 digit for the hexadecimal value and 1 space
  15. + (bytesPerLine - 1) / 8 // - 1 extra space every 8 characters from the 9th
  16. + 2; // 2 spaces
  17.  
  18. int lineLength = firstCharColumn
  19. + bytesPerLine // - characters to show the ascii value
  20. + Environment.NewLine.Length; // Carriage return and line feed (should normally be 2)
  21.  
  22. char[] line = (new String(' ', lineLength - 2) + Environment.NewLine).ToCharArray();
  23. int expectedLines = (bytesLength + bytesPerLine - 1) / bytesPerLine;
  24. StringBuilder result = new StringBuilder(expectedLines * lineLength);
  25.  
  26. for (int i = 0; i < bytesLength; i += bytesPerLine)
  27. {
  28. line[0] = HexChars[(i >> 28) & 0xF];
  29. line[1] = HexChars[(i >> 24) & 0xF];
  30. line[2] = HexChars[(i >> 20) & 0xF];
  31. line[3] = HexChars[(i >> 16) & 0xF];
  32. line[4] = HexChars[(i >> 12) & 0xF];
  33. line[5] = HexChars[(i >> 8) & 0xF];
  34. line[6] = HexChars[(i >> 4) & 0xF];
  35. line[7] = HexChars[(i >> 0) & 0xF];
  36.  
  37. int hexColumn = firstHexColumn;
  38. int charColumn = firstCharColumn;
  39.  
  40. for (int j = 0; j < bytesPerLine; j++)
  41. {
  42. if (j > 0 && (j & 7) == 0) hexColumn++;
  43. if (i + j >= bytesLength)
  44. {
  45. line[hexColumn] = ' ';
  46. line[hexColumn + 1] = ' ';
  47. line[charColumn] = ' ';
  48. }
  49. else
  50. {
  51. byte b = bytes[i + j];
  52. line[hexColumn] = HexChars[(b >> 4) & 0xF];
  53. line[hexColumn + 1] = HexChars[b & 0xF];
  54. line[charColumn] = (b < 32 ? 'ยท' : (char)b);
  55. }
  56. hexColumn += 3;
  57. charColumn++;
  58. }
  59. result.Append(line);
  60. }
  61. return result.ToString();
  62. }
Add Comment
Please, Sign In to add comment