Hex Dump From Byte Array - CSharp System

CSharp examples for System:Byte

Description

Hex Dump From Byte Array

Demo Code


using System.Windows.Forms;
using System.IO;/*from ww w. j a  va  2 s.com*/
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;

public class Main{
        public static string HexDumpFromByteArray(byte[] baArrayToDump)
        {
            string sRet = string.Empty;

            int iItemsPerLine = 16;

            StringBuilder oSB = new StringBuilder();

            string sHex = string.Empty;
            int iValue = 0;
            int iItem = 0;

            string sText = string.Empty;

            string sHeader1 = "       00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F  0123456789ABCDEF\r\n";
            string sHeader2 = "------+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-----------------\r\n";


            oSB.Append(sHeader1);
            oSB.Append(sHeader2);
            int pos = 0;
            foreach (byte oByte in baArrayToDump)
            {
                iValue = oByte;
                iItem += 1;

                if (char.IsControl((char)iValue))
                {
                    sText += " ";

                }
                else
                {
                    sText += string.Format("{0}", (char)iValue).PadLeft(1, ' ');
                }

                // Start of Line - Add position
                if (iItem == 1)
                {
                    oSB.Append(string.Format("{0000:X}", pos).PadLeft(4, '0'));
                    oSB.Append("  ");
                }

                if (iItem <= iItemsPerLine)
                {
                    oSB.Append(" ");
                    sHex = string.Format("{00:X}", iValue).PadLeft(2, '0');
                    oSB.Append(sHex);

                    // Text Representation of hex bits.
                    if (iItem == iItemsPerLine)
                    {

                        oSB.Append("  " + sText); // Add text representation of hex.
                        sText = string.Empty;
                        sHex = string.Format("\r\n");
                        oSB.Append(sHex);

                        sHex = string.Empty;
                        iItem = 0;
                    }

                }
            }

            if (iItem > 0 && iItem != iItemsPerLine)
            {
                int iPadLength = (3 * (16 - iItem)) + 2;
                string sPadding = String.Format("{0:X}", "").PadLeft(iPadLength, ' ');
                oSB.Append(sPadding);
                oSB.Append(sText); // Add text representation of hex.
                oSB.Append("\r\n");  
                pos++;
            }
            sRet = oSB.ToString();
            return sRet;

        }
}

Related Tutorials