首页  编辑  

度取和以十六进制显示文件

Tags: /超级猛料/Stream.File.流、文件和目录/文件操作/   Date Created:

read a binary file and display the byte values as ASCII?

author:P.Below

type

 TDisplayProc = procedure(const s: string) of object;

procedure ShowBinary(var Data; Count: Cardinal; DispProc: TDisplayProc);

implementation

procedure ShowBinary(var Data; Count: Cardinal; DispProc: TDisplayProc);

var

 line: string[80];

 i: Cardinal;

 p: PChar;

 nStr: string[4];

const

 posStart = 1;

 binStart = 7;

 ascStart = 57;

 HexChars: PChar = '0123456789ABCDEF';

begin

 p    := @Data;

 line := '';

 for i := 0 to Count - 1 do

 begin

   if (i mod 16) = 0 then

   begin

     if Length(line) > 0 then

       DispProc(line);

     FillChar(line, SizeOf(line), ' ');

     line[0] := Chr(72);

     nStr    := Format('%4.4X', [i]);

     Move(nStr[1], line[posStart], Length(nStr));

     line[posStart + 4] := ':';

   end;

   if p[i] >= ' ' then

     line[i mod 16 + ascStart] := p[i]

   else

     line[i mod 16 + ascStart] := '.';

   line[binStart + 3 * (i mod 16)]     := HexChars[(Ord(p[i]) shr 4) and $F];

   line[binStart + 3 * (i mod 16) + 1] := HexChars[Ord(p[i]) and $F];

 end;

 DispProc(line);

end;

procedure TForm1.Display(const S: string);

begin

 Memo1.Lines.Add(S);

end;

procedure TForm1.Button1Click(Sender: TObject);

var

 ms: TMemoryStream;

begin

 if Opendialog1.Execute then

 begin

   ms := TMemoryStream.Create;

   try

     ms.LoadFromfile(OpenDialog1.FileName);

     ShowBinary(ms.Memory^, ms.Size, Display);

   finally

     ms.Free

   end;

 end;

end;

img_23378.bmp (162.2KB)