本文整理自网络,侵删。
代码文件: -------------------------------------------------------------------------------- unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; Memo2: TMemo; Button1: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} {读文件为十六进制字符的函数} function ReadFileToHex(FileName: string): string; var bs: TBytesStream; i: Integer; begin Result := ''; if not FileExists(FileName) then Exit; bs := TBytesStream.Create; bs.LoadFromFile(FileName); for i := 0 to bs.Size - 1 do Result := Result + Format('%.2x ', [bs.Bytes[i]]); bs.Free; end; {测试} procedure TForm1.Button1Click(Sender: TObject); const FilePath = 'c:\temp\Text.txt'; begin Memo1.Lines.SaveToFile(FilePath); Memo2.Text := ReadFileToHex(FilePath); end; procedure TForm1.FormCreate(Sender: TObject); begin Button1.Caption := '保存并读出十六进制 (注意读出的 0D 0A 是换行符)'; end; end. -------------------------------------------------------------------------------- 窗体文件: -------------------------------------------------------------------------------- object Form1: TForm1 Left = 0 Top = 0 Caption = 'Form1' ClientHeight = 149 ClientWidth = 339 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object Memo1: TMemo Left = 0 Top = 0 Width = 160 Height = 124 Align = alLeft Lines.Strings = ( 'Memo1') ScrollBars = ssVertical TabOrder = 0 end object Memo2: TMemo Left = 179 Top = 0 Width = 160 Height = 124 Align = alRight Lines.Strings = ( 'Memo2') ScrollBars = ssVertical TabOrder = 1 end object Button1: TButton Left = 0 Top = 124 Width = 339 Height = 25 Align = alBottom Caption = 'Button1' TabOrder = 2 OnClick = Button1Click end end 读文件到十六进制的函数(Delphi 7 下可用)
{函数} function ReadFileToHex(FileName: string): string; var b: Byte; begin Result := ''; if not FileExists(FileName) then Exit; with TMemoryStream.Create do begin LoadFromFile(FileName); Position := 0; while Position < Size do begin ReadBuffer(b, 1); Result := Result + Format('%.2x ', [b]); end; Trim(Result); Free; end; end; {调用} procedure TForm1.Button1Click(Sender: TObject); var str: string; begin str := ReadFileToHex('c:\temp\test.txt'); ShowMessage(str); end;
相关阅读 >>
Delphi 如何把一个exe做为res加入到dll中,并在运行时生成exe文件执行
Delphi 10.3.x 截取字符串函数substring 和copy()常用字串符处理函数用法
更多相关阅读请进入《Delphi》频道 >>