CSharpFeeds - All your C# feeds in one place.

Sponsors

Friday, March 12, 2010

Hex Dump using LINQ (in 7 lines of code)

by Fabrice Marguerie via Fabrice's weblog on 3/12/2010 9:34:00 PM

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
email it!bookmark it!digg it!

Original Post: Hex Dump using LINQ (in 7 lines of code)

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us