Skip to content

Instantly share code, notes, and snippets.

@pleonex
Last active July 14, 2022 10:06
Show Gist options
  • Save pleonex/f04f1951fc4f784200eda2fd15c70676 to your computer and use it in GitHub Desktop.
Save pleonex/f04f1951fc4f784200eda2fd15c70676 to your computer and use it in GitHub Desktop.
Text-base hexadecimal viewer of the content of a Stream for C#
static string DumpStreamToHexString(Stream stream, long startPosition, int length)
{
const int BytesPerRow = 0x10;
const char horizontalBar = '─'; // or '|' for non-Unicode terminals
const char verticalBar = '│'; // or '-' for non-Unicode terminals
const char crossBar = '┼'; // or '|' for non-Unicode terminals
byte[] buffer = new byte[length];
int read = stream.Read(buffer);
var content = new StringBuilder();
var textLineBuilder = new StringBuilder();
// Header
content.AppendFormat("Offset {0} ", verticalBar);
for (int i = 0; i < BytesPerRow; i++) {
content.AppendFormat("{0:X2} ", i);
}
content.AppendFormat("{0} ASCII\n", verticalBar);
content.Append(new string(horizontalBar, 9));
content.Append(crossBar);
content.Append(new string(horizontalBar, 1 + (BytesPerRow * 3)));
content.Append(crossBar);
content.AppendLine(new string(horizontalBar, 1 + (BytesPerRow * 2)));
// For each line: offset, hex content and text content
content.AppendFormat("{0:X8} {1} ", startPosition, verticalBar);
for (int i = 0; i < read; i++) {
char ch = (buffer[i] >= 0x21 && buffer[i] <= 0x7F) ? (char)buffer[i] : '.';
textLineBuilder.AppendFormat("{0} ", ch);
if (i != 0 && ((i + 1) % BytesPerRow == 0)) {
content.AppendFormat("{0:X2} {2} {1}\n", buffer[i], textLineBuilder.ToString(), verticalBar);
content.AppendFormat("{0:X8} {1} ", startPosition + (i + 1), verticalBar);
textLineBuilder.Clear();
} else {
content.AppendFormat("{0:X2} ", buffer[i]);
}
}
return content.ToString();
}
// Create a test Stream
byte[] randomData = new byte[1024];
Random.Shared.NextBytes(randomData);
// Show the content via console
string hexDump = DumpStreamToHexString(stream, 0, (int)stream.Length);
Console.WriteLine(hexDump);
// Output:
// Offset | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F | ASCII
// ---------------------------------------------------------------------------------------------
// 00000000 | D6 3D A6 D7 ED 24 C1 35 10 11 5A 3D 29 49 FC AE | . = . . . $ . 5 . . Z = ) I . .
// 00000010 | 94 93 B6 37 8B 23 B0 68 78 54 70 DE D4 9A 0F 2C | . . . 7 . # . h x T p . . . . ,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment