delphi中将 4 个 Byte 合成 1 个 Integer 的五种方法

有4个字节类型的值,用移位或逻辑运算符怎么合成一个整数?
比如 $FFEEDDCC。

$FF
$EE
$DD
$CC

 



 

//方法 1: 共用内存procedure TForm1.Button1Click(Sender: TObject);
var
bf: record b1,b2,b3,b4: Byte end;

i: Integer absolute bf;
begin
bf.b1 := $CC;

bf.b2 := $DD;

bf.b3 := $EE;

bf.b4 := $FF;

ShowMessageFmt('%x', [i]);

//FFEEDDCC
end;
//方法 2: 位运算procedure TForm1.Button2Click(Sender: TObject);
var
i: Integer;
begin
i := $CC or ($DD shl 8) or ($EE shl 16) or ($FF shl 24);//不用括号也可
ShowMessageFmt('%x', [i]);

//FFEEDDCC
end;
//方法 3: 使用函数procedure TForm1.Button3Click(Sender: TObject);
var
i: Integer;
begin
i := MakeLong(MakeWord($CC,$DD),
MakeWord($EE,$FF));

ShowMessageFmt('%x', [i]);

//FFEEDDCCend;
//方法 4: 从静态数组...procedure TForm1.Button4Click(Sender: TObject);
var
bs: array[0..3] of Byte;

P: PInteger;
begin
bs[0] := $CC;

bs[1] := $DD;

bs[2] := $EE;

bs[3] := $FF;

P := @bs;

ShowMessageFmt('%x', [P^]);

//FFEEDDCC
end;
//方法 5: 从动态数组...procedure TForm1.Button5Click(Sender: TObject);
var
bs: array of Byte;

P: PInteger;
begin
SetLength(bs, 4);

bs[0] := $CC;

bs[1] := $DD;

bs[2] := $EE;

bs[3] := $FF;

P := @bs[0];

ShowMessageFmt('%x', [P^]);

//FFEEDDC
Cend;
-------------------------------------------------------------------------------
1.可以直接Copymemory或者Move
2.可以用变体类型的结构体.
type
   TWordOfInt = array[0..2-1] of WORD;
   TByteOfInt = array[0..4-1] of Byte;
   TIntRec = packed record //定义一个辅助类型,这样转换非常快,而且方便
     case Integer of
       0: (IntValue: Integer);
       1: (Low, High: Word);
       2: (Words: TWordOfInt);
       3: (Bytes: TByteOfInt);
   end;

//方法一,借助TIntRec,来转换
var
   Int : Integer;
   Bytes : TByteOfInt;
begin
   int := 100;

   Bytes := TIntRec(int).Bytes;//integer转字节数组
   Int :=  TIntRec(Bytes).IntValue; //Byte数组转Integer

end;

//方法二, 直接用TIntRec,不转换.根本不耗费一点点CPU的时间
var
   value : TIntRec;
begin
   value.IntValue := 100; //看成Integer
   //下面是看成Byte数组用
   value.Bytes[0] := 1;
   value.Bytes[1] := 1;
   value.Bytes[2] := 1;
   value.Bytes[3] := 1;
end;

http://w-tingsheng.blog.163.com/blog/static/2505603420122643224621/

原文地址:https://www.cnblogs.com/760044827qq/p/3938915.html