Delphi XE3 -> Integer to array of Bytes

后端 未结 5 1341
野趣味
野趣味 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:22

    As commented, you do not need to move the data to access it as both byte and integer.

    Your original array of byte could be accessed as an array of integer by type casting.

    type
      TArrayInteger = array of Integer;
    ...
    for i := 0 to Pred(Length(source)) div SizeOf(Integer) do
      WriteLn(TArrayInteger(source)[i]);
    

    Often I hide these type casts in a class. In XE3 there is possibility to declare class helpers for simple types, like string,byte,integers, etc. See TStringHelper for example. The same goes for array of simple types.

    Here is an example using a record helper:

    type
      TArrayByte = array of Byte;
      TArrayInteger = array of Integer;
    
      TArrayByteHelper = record helper for TArrayByte
      private
        function GetInteger(index : Integer) : Integer;
        procedure SetInteger(index : Integer; value : Integer);
      public
        property AsInteger[index : Integer] : Integer read GetInteger write SetInteger;
      end;
    
    function TArrayByteHelper.GetInteger(index: Integer): Integer;
    begin
      Result := TArrayInteger(Self)[index];
    end;
    
    procedure TArrayByteHelper.SetInteger(index: Integer; value: Integer);
    begin
      TArrayInteger(Self)[index] := value;
    end;
    

    Use it like this:

    Var
      source : TArrayByte;
      i : Integer;
    begin
      SetLength(source,8);
      for i := 0 to 7 do
        source[i] := i;
      for i := 0 to 1 do
        WriteLn(Format('%8.8X',[source.AsInteger[i]]));
      ReadLn;
    end.
    

提交回复
热议问题