字符串相互转字符数组 string byte 数组 array of 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,Integer,byte)