delphi 动态字节数组的转换Tbytes String ANSIString及TBytes之间的转换

一、string转为ansistring

1、直接赋值 (有警告)

2、ansistring()类型强制转换。(无警告)

二、ansistring 转为string

1、直接赋值 (有警告)

2、string()类型强制转换。(无警告)

三、string 转为Tbytes

1、bytes:= bytesof(str) 已转为ansi编码

2、bytes:= widebytesof(str) UNICODE 编码

四、ansistring 转为Tbytes

1、bytes:= bytesof(str) ansi编码

2、bytes:= widebytesof(string(str)) UNICODE 编码

五、Tbytes 转为string

1、 str:=stringof(bytes) Tbytes 为ansi编码

2、 str:=widestringof(bytes) Tbytes 为unicode编码

六、PChar转String

用StrPas函数,StrPas(PChar):AnsiString;

{转换 TBytes Integer}

procedureTForm1.Button1Click(Sender: TObject);

var

bs: TBytes; {TBytes 就是 Byte 的动态数组}

i: Integer;

begin

{它应该和 Integer 一样大小才适合转换}

SetLength(bs, 4);

bs[0] := $10;

bs[1] := $27;

bs[2] := 0;

bs[3] := 0;

{因为 TBytes 是动态数组, 所以它的变量 bs 是个指针; 所以先转换到 PInteger} i := PInteger(bs)^; ShowMessage(IntToStr(i)); {10000}

end;

{从 Bytes 静态数组到 Integer 的转换会方便些}

procedureTForm1.Button2Click(Sender: TObject);

var

bs: array[0..3] ofByte;

i: Integer;

begin

bs[0] := $10;

bs[1] := $27;

bs[2] := 0;

bs[3] := 0;

i := Integer(bs);

ShowMessage(IntToStr(i)); {10000}

end;

{转换到自定义的结构}

procedureTForm1.Button3Click(Sender: TObject);

type

TData = packedrecord

a: Integer;

b: Word;

end;

var

bs: array[0..5] ofByte; {这个数组应该和结构大小一直}

data: TData;

begin

FillChar(bs, Length(bs), 0);

bs[0] := $10;

bs[1] := $27;

data := TData(bs);

ShowMessage(IntToStr(data.a)); {10000}

end;

{转换给自定义结构的一个成员}

procedureTForm1.Button4Click(Sender: TObject);

type

TData = packedrecord

a: Integer;

b: Word;

end;

var

bs: array[0..3] ofByte;

data: TData;

begin

FillChar(bs, Length(bs), 0);

bs[0] := $10;

bs[1] := $27;

data.a := Integer(bs);

ShowMessage(IntToStr(data.a)); {10000}

end;