我正在尝试将此代码转换为Delphi 7。在Python中,它将十六进制字节转换为大端字节:
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]到目前为止,我的Delphi代码:
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;在Delphi中,转换为大端的正确方法是什么?
发布于 2022-01-15 16:30:27
你就快到了,除了实际情况相反。考虑通过“手动”交换每个字节来单独完成该部分:
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;这是一个颇有教育意义的例子。另见how to convert big-endian numbers to native numbers delphi。缩进Pascal代码并不是强制性的,但它大大提高了阅读能力。
https://stackoverflow.com/questions/70722846
复制相似问题