读十六进制文本到 Btye 数组的函数

unit Unit1;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls;

type

TForm1 = class(TForm)

Button1: TButton;

Memo1: TMemo;

procedure Button1Click(Sender: TObject);

end;

var

Form1: TForm1;

implementation

{$R *.dfm}

{把十六进制文本载入一个 Byte 数组的函数}

procedure HexToArr(const FileName: string; var arr: TBytes);

var

str: string;

count: Integer;

i: Integer;

begin

if not FileExists(FileName) then Exit;

with TStringList.Create do begin

LoadFromFile(FileName);

str := Text;

Free;

end;

str := StringReplace(str, ' ', '', [rfReplaceAll]); {清除空格}

count := Length(str);

SetLength(arr, (count-1) div 2);

for i := 0 to count - 2 do if Odd(i) then

arr[i div 2] := StrToIntDef('$' + str[i] + str[i+1], 1);

end;

{测试}

procedure TForm1.Button1Click(Sender: TObject);

const

HexTxtFile = 'c:\temp\Hex.txt'; {一定要是十六进制的文本格式, 由 0-F 十六个字符组成的}

var

MyArr: TBytes;

str: string;

i: Integer;

begin

{调用函数}

HexToArr(HexTxtFile, MyArr);

{在 Memo 中看看, 落实下}

str := '';

for i := 0 to Length(MyArr) - 1 do

str := str + Format('%.2x ', [MyArr[i]]);

Memo1.Text := TrimRight(str);

end;

end.


 
   

窗体文件:

object Form1: TForm1

Left = 0

Top = 0

Caption = 'Form1'

ClientHeight = 136

ClientWidth = 317

Color = clBtnFace

Font.Charset = DEFAULT_CHARSET

Font.Color = clWindowText

Font.Height = -11

Font.Name = 'Tahoma'

Font.Style = []

OldCreateOrder = False

PixelsPerInch = 96

TextHeight = 13

object Button1: TButton

Left = 234

Top = 103

Width = 75

Height = 25

Caption = 'Button1'

TabOrder = 0

OnClick = Button1Click

end

object Memo1: TMemo

Left = 0

Top = 0

Width = 317

Height = 97

Align = alTop

Lines.Strings = (

'Memo1')

ScrollBars = ssBoth

TabOrder = 1

end

end

 

 

[Error] Unit1.pas(24): Undeclared identifier: 'TBytes'

type TBytes = array of Byte;

你可能感兴趣的:(十六进制)