天天看點

轉換 Byte 數組到 ... - 回複

轉換 Byte 數組到 ... - 回複 "高群" 的問題

問題來源: https://blog.51cto.com/u_14617575/2748009

{轉換 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;