Delphi XE3 -> Integer to array of Bytes

后端 未结 5 1328
野趣味
野趣味 2021-01-02 22:52

I have a data structure:

data = array of integer;

I have filled it from an

source = array of byte;

with

5条回答
  •  庸人自扰
    2021-01-02 23:07

    Hmmm... I see an answer using Move and one using shifts, but what about a simple cast?:

    var
      I: Integer;
      B: array[0..3] of Byte;
    begin
      // from bytes to integer:
      I := PInteger(@B)^;
      // from integer to bytes:
      PInteger(@B)^ := I;
    

    Or with your arrays:

    data[i] := PInteger(@source[offset])^;
    

    and vice versa:

    // get low byte
    source[offset] := PByte(@data[i])^; // or := PByte(@data[i])[0];
    // get second byte
    secondByte := PByte(@data[i])[1]; // or := (PByte(@data[i]) + 1)^;
    

    or

    PInteger(@source[offset])^ := data[i];
    

    As you see, you can get a long way by casting to pointers. This does not actually take the pointer, the compiler is clever enough to access the items directly.

提交回复
热议问题