CSharp examples for System:Hex
Hex Dump From File
using System.Windows.Forms; using System.IO;/* w ww .ja v a 2 s. co m*/ using System.Text; using System.Linq; using System.Collections.Generic; using System; public class Main{ public static bool HexDumpFromFile(string sFile, ref string sDump) { bool bRet = false; int iItemsPerLine = 16; StringBuilder oSB = new StringBuilder(); BinaryReader b = null; string sHex = string.Empty; int iValue = 0; int iItem = 0; int iReadSize = sizeof(byte); 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"; string path = sFile.Trim(); if (File.Exists(path)) { try { oSB.Append(sHeader1); oSB.Append(sHeader2); b = new BinaryReader(File.Open(path, FileMode.Open)); int pos = 0; int length = (int)b.BaseStream.Length; while (pos < length) { //iValue = b.ReadInt32(); //iValue = b.ReadChar(); iValue = b.ReadByte(); 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++; } pos += iReadSize; // Point to next. } b.Close(); b = null; sDump = oSB.ToString(); bRet = true; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "Error Reading File"); bRet = false; } } return bRet; } }