码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-09-15 09:54:18      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   os   ar   for   数据   2014   div   

 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();
        }

截图示例:
bubuko.com,布布扣

 

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

标签:blog   http   io   os   ar   for   数据   2014   div   

原文地址:http://www.cnblogs.com/twzy/p/3972179.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!