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 00000016: 65 00 72 00 73 00 69 00 6F 00 6E 00 3D 00 22 00000032: 31 00 2E 00 30 00 22 00 20 00 65 00 6E 00 63 00000048: 6F 00 64 00 69 00 6E 00 67 00 3D 00 22 00 75 00000064: 3E 00
Eric White reports that he typically notices that declarative code is only 20% as long as imperative code.
Original Post: Hex Dump using LINQ (in 7 lines of code)
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.