您现在的位置:首页 >> 基础算法 >> window基础 >> 内容

Delphi把转换Byte数组到Integer

时间:2011/9/3 15:34:07 点击:

  核心提示:{转换 TBytes 到 Integer}procedure TForm1.Button1Click(Sender: TObject);var bs: TBytes; {TBytes 就是 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;

Tags:转换 数组 
作者:万一 来源:转载
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • 盒子文章(www.2ccc.com) © 2024 版权所有 All Rights Reserved.
  • 沪ICP备05001939号