字符串相互转字符数组 string byte 数组 array of byte

procedure TForm1.Button1Click(Sender: TObject);
const
s = 'abcd1234';
var
arr: array of Byte;
i: integer;
s2: string;
begin
//string to byte array
SetLength(arr,Length(s));
CopyMemory(arr,PChar(s),Length(s));
for i := 0 to High(arr) - 1 do
ShowMessage(chr(arr[i]));

//byte array to string
SetLength(s2,Length(arr));
CopyMemory(PChar(s2),arr,Length(arr));
ShowMessage(s2);
end;

转换 Byte 数组到 ... 问题

{转换 TBytes 到 Integer}
procedure TForm1.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 的转换会方便些}
procedure TForm1.Button2Click(Sender: TObject);
var
bs: array[0..3] of Byte;
i: Integer;
begin
bs[0] := $10;
bs[1] := $27;
bs[2] := 0;
bs[3] := 0;

i := Integer(bs);
ShowMessage(IntToStr(i)); {10000}
end;

{转换到自定义的结构}
procedure TForm1.Button3Click(Sender: TObject);
type
TData = packed record
    a: Integer;
    b: Word;
end;
var
bs: array[0..5] of Byte; {这个数组应该和结构大小一直}
data: TData;
begin
FillChar(bs, Length(bs), 0);
bs[0] := $10;
bs[1] := $27;

data := TData(bs);
ShowMessage(IntToStr(data.a)); {10000}
end;

{转换给自定义结构的一个成员}
procedure TForm1.Button4Click(Sender: TObject);
type
TData = packed record
    a: Integer;
    b: Word;
end;
var
bs: array[0..3] of Byte;
data: TData;
begin
FillChar(bs, Length(bs), 0);
bs[0] := $10;
bs[1] := $27;

data.a := Integer(bs);
ShowMessage(IntToStr(data.a)); {10000}
end;

你可能感兴趣的:(String)