Was messing around with byte arrays a lot in LINQPad this week and really wanted a pretty hex print of the contents of the array so wrote this:
public static object HexDump(byte[] data)
{
	return data
		.Select((b, i) => new { Byte = b, Index = i })
		.GroupBy(o => o.Index / 16)
		.Select(g => 
			g
			.Aggregate(
				new { Hex = new StringBuilder(), Chars = new StringBuilder() },
				(a, o) => {a.Hex.AppendFormat("{0:X2} ", o.Byte); a.Chars.Append(Convert.ToChar(o.Byte)); return a;},
				a => new { Hex = a.Hex.ToString(), Chars = a.Chars.ToString() }
			)
		)
		.ToList()
		.Dump();
}You use it like this:
byte[] text = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog");
HexDump(text);...and it will produce output akin to:
 

1 comment:
Nice :)
Post a Comment