Delphi: show contents of file in Hexadecimal


Posted by webmaster Guido on February 02, 2003

In Reply to: Hexadecimal Bitmaps posted by topgub on February 02, 2003:
: Can some one please tell me how i can get the hexadecimal from a bitmap for displaying in a memo box?
---------

The following example lets you view the binary contents of *any* file in hexadecimal format. In the parameter "FileName" you provide the full path to the file, for example: FileViewHex('c:\data\test.bmp')
For clarity, I left out all error checking. It's also not optimized for large files, so start your testing with small bitmaps ;-)

procedure TForm1.FileViewHex(FileName: string);
const
  MaxLineLength = 16 * 3; // each byte displayed with 2 characters plus a space
  BufferSize = 4096;
var
  DataFile: File;
  Buffer: array[1..BufferSize] of byte;
  BytesRead, I: integer;
  HexByte, Line: string;
begin
  AssignFile(DataFile, FileName);
  Reset(DataFile, 1);
  Memo1.Clear;
  while not Eof(DataFile) do begin
    BlockRead(DataFile, Buffer, BufferSize, BytesRead);
    Line := '';
    for I := 1 to BytesRead do begin
      HexByte := IntToHex(Buffer[I], 1); // convert a byte to hexadecimal
      // Add leading 0 if result is shorter than 2, easier to read...
      if Length(HexByte) < 2 then HexByte := '0' + HexByte;
      Line := Line + HexByte + ' ';
      if Length(Line) >= MaxLineLength then begin
        Memo1.Lines.Add(Line);
        Line := '';
      end;
    end;
  end;
  // If not already added, add last line to TMemo
  if Length(Line) > 0 then Memo1.Lines.Add(Line); 
  CloseFile(DataFile);
end;


[ DelphiLand Discussion Forum ]