0

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?

AmigoJack
  • 5,234
  • 1
  • 15
  • 31
Maaz
  • 131
  • 8
  • 1
    What do you mean convert to big endian? Delphi Integer is kittle endian. Do you mean interpret the byte array as being big endian? Your delphi code makes no attempt to handle endianness. Also your code will read off the end of the array if its length is not an example multiple of 4 – David Heffernan Jan 15 '22 at 15:50
  • In python keydata is converted to be big endian i am not sure how i am supposed to do this in Delphi length of keydata is 32 btw – Maaz Jan 15 '22 at 15:57
  • Digging in to Unpack in python i found ">" is for big-endian and "I" unsigned int – Maaz Jan 15 '22 at 16:03
  • no that's not what happens in Python. The data is interpreted as big endian and converted to host endian. – David Heffernan Jan 15 '22 at 17:30
  • The other thing to say is that the Python code doesn't work with hex bytes. It works with bytes. Hex is just one representation. 0xff is the same value as 255. This might sound pedantic but it matters. Having a really clear understanding of this will help you tackle such problems effectively. – David Heffernan Jan 16 '22 at 10:04

1 Answers1

1

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.

AmigoJack
  • 5,234
  • 1
  • 15
  • 31