我正在嘗試將此代碼轉換為 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]
到目前為止我的德爾福代碼:
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中轉換為大端的正確方法是什么?
uj5u.com熱心網友回復:
你快到了,除了實際的位元組序反轉。考慮通過“手動”交換每個位元組來自行完成該部分:
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;
這是一個頗具教育意義的例子。另請參閱如何將 big-endian 數字轉換為本機數字 delphi。縮進 Pascal 代碼不是強制性的,但它可以大大提高閱讀能力。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412473.html
標籤:
