Csharp/C Sharp/Data Types/HEX

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

The hex dump program

using System;
using System.IO;
  class Class1 {
       public static string PadZero( string s, int len ) {
         string temp = s;
         for ( int i=s.Length; i<len; ++i ){
           temp = "0" + temp;
         } 
         return temp;
       }
       static void Main(string[] args) {
             StreamReader sr = new StreamReader( "test.cs" );
             string line = "";
             int nCounter = 0;
             int nOffset = 0;
             while ( (line = sr.ReadLine()) != null ) {
                 for ( int i=0; i<line.Length; ++i ) {
                    int c = (int)line[i];
                    string fmt = String.Format("{0:x}", c);
            
                    if ( fmt.Length == 1 )
                     fmt = PadZero(fmt, 2);
            
                    if ( nOffset % 16 == 0 ) {
                     string offsetFmt = nOffset.ToString();
                     Console.Write(PadZero(offsetFmt,5)+": ");
                    }
            
                    Console.Write(fmt + " ");
                    if ( nCounter == 15 ) {
                      Console.Write("\n");
                      nCounter = 0;
                    } else {
                     nCounter ++;
                    } 
                    nOffset ++;
                 }
             }
       }
  }