Created
February 7, 2018 23:21
-
-
Save Unknown6656/4a57263d3b625f0cc8d335535b4be497 to your computer and use it in GitHub Desktop.
A C# function to hex-dump a given byte array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Dumps the given byte array as hexadecimal text viewer | |
/// </summary> | |
/// <param name="value">Byte array to be dumped</param> | |
public static void HexDump(this byte[] value) | |
{ | |
if ((value?.Length ?? 0) == 0) | |
return; | |
ConsoleColor fc = Console.ForegroundColor; | |
ConsoleColor bc = Console.BackgroundColor; | |
bool cv = Console.CursorVisible; | |
int w = Console.WindowWidth - 16; | |
int l = (w - 3) / 4; | |
byte b; | |
l -= l % 16; | |
int h = (int)Math.Ceiling((float)value.Length / l); | |
Console.CursorVisible = false; | |
Console.WriteLine(); | |
Console.ForegroundColor = ConsoleColor.White; | |
Console.BackgroundColor = ConsoleColor.Black; | |
Console.WriteLine($" {value.Length} bytes:\n\n"); | |
Console.CursorLeft += 8; | |
for (int j = 0; j <= l; j++) | |
{ | |
Console.CursorTop--; | |
Console.Write($" {j / 16:x}"); | |
Console.CursorLeft -= 3; | |
Console.CursorTop++; | |
Console.Write($" {j % 16:x}"); | |
} | |
Console.WriteLine(); | |
fixed (byte* ptr = value) | |
for (int i = 0; i < h; i++) | |
{ | |
Console.Write($"{i * l:x8}: "); | |
bool cflag; | |
for (int j = 0; (j < l) && (i * l + j < value.Length); j++) | |
{ | |
b = ptr[i * l + j]; | |
cflag = *((int*)(ptr + i * l + (j / 4) * 4)) != 0; | |
Console.ForegroundColor = b == 0 ? cflag ? ConsoleColor.White : ConsoleColor.DarkGray : ConsoleColor.Yellow; | |
Console.Write($"{b:x2} "); | |
} | |
Console.ForegroundColor = ConsoleColor.White; | |
Console.CursorLeft = 3 * l + 11; | |
Console.Write("| "); | |
for (int j = 0; (j < l) && (i * l + j < value.Length); j++) | |
{ | |
byte _ = ptr[i * l + j]; | |
bool ctrl = (_ < 0x20) || ((_ >= 0x7f) && (_ <= 0xa0)); | |
if (ctrl) | |
Console.ForegroundColor = ConsoleColor.Red; | |
Console.Write(ctrl ? '.' : (char)_); | |
Console.ForegroundColor = ConsoleColor.White; | |
} | |
Console.Write("\n"); | |
} | |
Console.WriteLine(); | |
Console.CursorVisible = cv; | |
Console.ForegroundColor = fc; | |
Console.BackgroundColor = bc; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment