If there are four bytes of value, how can we synthesize an integer using a shift or logical operator?
For example, $ ffeeddcc.
High
$ FF
$ EE
$ Dd
$ CC
Low
// Method 1: Shared Memory 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;
// Method 2: bitwise procedure tform1.button2click (Sender: tobject );
VaR
I: integer;
Begin
I: = $ cc or ($ dd SHL 8) or ($ EE SHL 16) or ($ FF SHL 24); // No parentheses are required.
Showmessagefmt ('% x', [I]);
// Ffeeddcc
End;
// Method 3: Use the procedure tform1.button3click function (Sender: tobject );
VaR
I: integer;
Begin
I: = makelong (makeword ($ CC, $ dd ),
Makeword ($ EE, $ ff ));
Showmessagefmt ('% x', [I]);
// Ffeeddccend;
// Method 4: from the static array... 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;
// Method 5: from the dynamic array... 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 or move 2. struct types of variant types can be used. Type Twordofint = array [0 .. 2-1] of word; Tbyteofint = array [0 .. 4-1] of byte; Tintrec = packed record // define a secondary type, which is fast and convenient for conversion. Case INTEGER 0: (intvalue: integer ); 1: (low, high: Word ); 2: (words: twordofint ); 3: (Bytes: tbyteofint ); End;
// Method 1. Use tintrec to convert VaR INT: integer; Bytes: tbyteofint; Begin INT: = 100;
Bytes: = tintrec (INT). bytes; // integer to byte array INT: = tintrec (bytes). intvalue; // convert byte array to integer
End;
// Method 2: directly use tintrec without conversion. It does not take a little CPU time. VaR Value: tintrec; Begin Value. intvalue: = 100; // It is regarded as an integer. // The following is used as a byte array 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/
Five methods for combining four bytes into one integer in Delphi