class Program
{
static void Main(string[] args)
{
WriteToConsole(StrToByteArray(
"Hello world!\nit's a fine day. More data..\nHere.. and" +
"here.. data is my friend :-)...\n....."));
Console.ReadLine();
}
///
/// Yawn.
///
/// String.
/// Byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
///
/// Formats a data into 16-byte rows followed by an ASCII representation.
///
/// The data to format.
/// A string representing the data.
public static string Format(byte[] data)
{
StringBuilder sb = new StringBuilder();
sb.Append("0000 ");
StringBuilder lineAscii = new StringBuilder(16, 16);
for (int i = 0; i < data.Length; i++)
{
#region Build the end-of-line ascii
char curData = (char)data[i];
if (char.IsLetterOrDigit(curData) || char.IsPunctuation(curData) ||
char.IsSymbol(curData) || curData == ' ')
{
lineAscii.Append(curData);
}
else
{
lineAscii.Append('.');
}
#endregion
sb.AppendFormat("{0:X2} ", data[i]);
if ((i + 1) % 8 == 0)
{
sb.Append(" ");
}
if (((i + 1) % 16 == 0) || ((i + 1) == data.Length))
{
if ((i + 1) == data.Length && ((i + 1) % 16) != 0)
{
int lenOfCurStr = ((i % 16) * 3);
if ((i % 16) > 8) lenOfCurStr++;
for (int j = 0; j < (47 - lenOfCurStr); j++)
sb.Append(' ');
}
sb.AppendFormat(" {0}", lineAscii.ToString());
lineAscii = new StringBuilder(16, 16);
sb.Append(Environment.NewLine);
if (data.Length > (i + 1))
{
sb.AppendFormat("{0:X4} ", i + 1);
}
}
}
return sb.ToString();
}
///
/// Writes a series of bytes to the console, printing them in 16-byte rows
/// followed by an ASCII representation.
///
/// The data to print.
public static void WriteToConsole(byte[] data)
{
Console.WriteLine(Format(data));
}
}
Output:
0000 48 65 6C 6C 6F 20 77 6F 72 6C 64 21 0A 69 74 27 Hello world!.it'
0010 73 20 61 20 66 69 6E 65 20 64 61 79 2E 20 4D 6F s a fine day. Mo
0020 72 65 20 64 61 74 61 2E 2E 0A 48 65 72 65 2E 2E re data...Here..
0030 20 61 6E 64 68 65 72 65 2E 2E 20 64 61 74 61 20 andhere.. data
0040 69 73 20 6D 79 20 66 72 69 65 6E 64 20 3A 2D 29 is my friend :-)
0050 2E 2E 2E 0A 2E 2E 2E 2E 2E .........