Dump IEnumerable byte - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Dump IEnumerable byte

Demo Code

//     This software is dual-licensed: you can redistribute it and/or modify
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from  ww  w  .j  a  v a  2s  .  c o m*/

public class Main{
        public static string Dump(this IEnumerable<byte> collection)
        {
            var output = new StringBuilder();
            var hex = new StringBuilder();
            var text = new StringBuilder();
            int i = 0;
            foreach (byte value in collection)
            {
                if (i > 0 && ((i % 16) == 0))
                {
                    output.Append(hex);
                    output.Append(' ');
                    output.Append(text);
                    output.Append(Environment.NewLine);
                    hex.Clear(); text.Clear();
                }
                hex.Append(value.ToString("X2"));
                hex.Append(' ');
                text.Append(string.Format("{0}", (char.IsWhiteSpace((char)value) && (char)value != ' ') ? '.' : (char)value)); // prettify text
                ++i;
            }
            var hexstring = hex.ToString();
            if (text.Length < 16)
            {
                hexstring = hexstring.PadRight(48); // pad the hex representation in-case it's smaller than a regular 16 value line.
            }
            output.Append(hexstring);
            output.Append(' ');
            output.Append(text);
            return output.ToString();
        }
}

Related Tutorials