1. 程式人生 > >動態位元組陣列的轉換 Tbytes String、ANSIString及TBytes之間的轉換

動態位元組陣列的轉換 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}
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
--------------------- 
作者:古今飛揚 
來源:CSDN 
原文:https://blog.csdn.net/GzyCSDN/article/details/77481346 
版權宣告:本文為博主原創文章,轉載請附上博文連結!