/
ByteArrayExtensions.cs
77 lines (64 loc) · 2.41 KB
/
ByteArrayExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Text;
namespace System.Reactive
{
public static class ByteArrayExtensions
{
/// <summary>
/// Displays the byte array as hex-dump, like within a debugger
/// </summary>
/// <param name="bytes">array to display as hex</param>
/// <returns></returns>
public static string ToHexDump(this byte[] bytes)
{
StringBuilder sb = new StringBuilder();
int lineOffset = 0;
while (lineOffset < bytes.Length)
{
// output line offset from the start of the buffer
sb.Append(lineOffset.ToString("x4"));
sb.Append(": ");
// output hex dump
int endOffset = Math.Min(lineOffset + 16, bytes.Length);
int index = 0;
for (int byteOffset = lineOffset; byteOffset < endOffset; byteOffset++)
{
if (index == 8)
sb.Append(' ');
index++;
sb.Append(bytes[byteOffset].ToString("x2"));
sb.Append(' ');
}
// fill in the blanks if we cut off without completing entire line
int lineLength = endOffset - lineOffset;
if (lineLength < 16)
{
for (int i = lineLength; i < 16; i++ )
{
if (index == 8)
sb.Append(' ');
index++;
sb.Append(" ");
}
}
sb.Append(" ");
// output character dump
index = 0;
for (int byteOffset = lineOffset; byteOffset < endOffset; byteOffset++)
{
index++;
byte b = bytes[byteOffset];
if (b > 32)
sb.Append((char)b);
else
sb.Append('.');
if (index == 8)
sb.Append(' ');
}
sb.AppendLine();
lineOffset += 16;
}
return sb.ToString();
}
}
}