ASP.NET Hosting

Hex Dump using LINQ (in 7 lines of code)

Eric White has posted an interesting LINQ query on his blog that shows how to create a Hex Dump in something like 7 lines of code.

Of course, this is not production grade code, but it's another good example that demonstrates the expressiveness of LINQ.

Here is the code:

byte[] ba = File.ReadAllBytes("test.xml");
int bytesPerLine = 16;
string hexDump = ba.Select((c, i) => new { Char = c, Chunk = i / bytesPerLine })
    .GroupBy(c => c.Chunk)
    .Select(g => g.Select(c => String.Format("{0:X2} ", c.Char))
        .Aggregate((s, i) => s + i))
    .Select((s, i) => String.Format("{0:d6}: {1}", i * bytesPerLine, s))
    .Aggregate("", (s, i) => s + i + Environment.NewLine);
Console.WriteLine(hexDump);

Here is a sample output:

000000: FF FE 3C 00 3F 00 78 00 6D 00 6C 00 20 00 76 00
000016: 65 00 72 00 73 00 69 00 6F 00 6E 00 3D 00 22 00
000032: 31 00 2E 00 30 00 22 00 20 00 65 00 6E 00 63 00
000048: 6F 00 64 00 69 00 6E 00 67 00 3D 00 22 00 75 00
000064: 3E 00

Eric White reports that he typically notices that declarative code is only 20% as long as imperative code.


Cross-posted from http://linqinaction.net

No Comments