Search code examples
pythondelphidelphi-7endianness

Python code to Delphi 7 conversion: endianess


I am trying to convert this code to Delphi 7. In Python it converts hex bytes to big endian:

keydata=[0,0,0,0,0,0,0,0]
for i in range(0,len(data),4):
 Keydata[i//4]=unpack(">I",data[i:i+4])[0]

My Delphi code so far:

Var
Keydata:array of integer;

Setlength(keydata,8);
While i <= Length(data)-1 do begin
Move(data[i], keydata[i div 4], 4);
Inc(i,4);
End;

What is the correct way of converting to big endian in Delphi?


Solution

  • You're almost there, except for the actual endianess reverse. Consider doing that part on your own by exchanging each byte "manually":

    var
      keydata: Array of Byte;  // Octets = 8bit per value; Integer would be 32bit
      i: Integer;  // Going through all bytes of the array, 4 at once
      first, second: Byte;  // Temporary storage
    begin
      SetLength( keydata, 8 );
      for i:= 0 to 7 do keydata[i]:= i;  // Example: the array is now [0, 1, 2, 3, 4, 5, 6, 7]
    
      i:= 0;  // Arrays start with index [0]
      while i< Length( keydata ) do begin
        first:= keydata[i];
        second:= keydata[i+ 1];
        keydata[i]:= keydata[i+ 3];  // 1st byte gets overwritten
        keydata[i+ 1]:= keydata[i+ 2];
        keydata[i+ 2]:= second;
        keydata[i+ 3]:= first;  // Remembering the 1st byte
    
        Inc( i, 4 );  // Next 4 bytes
      end;
    
      // keydata should now be [3, 2, 1, 0, 7, 6, 5, 4]
    end;
    

    This is a rather educational example. See also how to convert big-endian numbers to native numbers delphi. Indenting Pascal code is not mandatory, but it improves reading a lot.