動態字節數組的轉換 Tbytes String、ANSIString及TBytes之間的轉換

1、string轉爲ansistring
一、直接賦值 (有警告)
二、ansistring()類型強制轉換。(無警告)

2、ansistring 轉爲string

一、直接賦值 (有警告)
二、string()類型強制轉換。(無警告)

3、string 轉爲Tbytes

一、bytes:= bytesof(str) 已轉爲ansi編碼
二、bytes:= widebytesof(str) UNICODE 編碼

4、ansistring 轉爲Tbytes

一、bytes:= bytesof(str) ansi編碼
二、bytes:= widebytesof(string(str)) UNICODE 編碼

5、Tbytes 轉爲string

一、 str:=stringof(bytes) Tbytes 爲ansi編碼
二、 str:=widestringof(bytes) Tbytes 爲unicode編碼

6、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 
版權聲明:本文爲博主原創文章,轉載請附上博文連接!
相關文章
相關標籤/搜索