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