数据按照十六进制文本输入,可自动调节输出宽度

 public static string PrintHex(byte[] data, int rowLength)
        {
            if (rowLength % 2 == 1)
                throw new ArgumentException("必须是偶数!");

            var buffer = new StringBuilder();
            string segmentNumber = "";
            string bytes = "";
            string ascii = "";

            for (int i = 1; i <= data.Length; i++)
            {
                bytes += (data[i - 1].ToString("X2")) + " ";
                if (data[i - 1] < 0x21 || data[i - 1] > 0x7e)
                {
                    ascii += ".";
                }
                else
                {
                    ascii += Encoding.ASCII.GetString(new byte[1] { data[i - 1] });
                }
                if (i % rowLength != 0 && i % (rowLength / 2) == 0)
                {
                    bytes += " ";
                    ascii += " ";
                }
                if (i % rowLength == 0)
                {
                    segmentNumber = ((((i - rowLength) / rowLength) * rowLength).ToString("X4"));
                    buffer.AppendLine(segmentNumber + "  " + bytes + "  " + ascii);
                    bytes = "";
                    ascii = "";

                    continue;
                }
                if (i == data.Length)
                {
                    segmentNumber = (((((i - rowLength) / rowLength) + 1) * rowLength).ToString("X4"));
                    buffer.AppendLine(segmentNumber + "  " + bytes.PadRight(rowLength * 3 + 1, ' ') + "  " + ascii);
                }
            }
            return buffer.ToString();
        }

截图示例:

 

posted @ 2014-09-15 09:22  淡墨青云  阅读(288)  评论(0编辑  收藏  举报