将pyhon代码转换为delphi的问题

问题描述 投票:0回答:1

我需要将 python 代码转换为 delphy,但我不能。

Python代码是:

def crc32(data: bytes, initial):
crc = initial
for x in data:
    for k in range(8):
        if ((crc ^ x) & 0x01) == 1:
            crc = crc >> 1
            crc = crc ^ 0x04c11db7
        else:
            crc = crc >> 1
        x = x >> 1
crc &= 0xffffffff
return crc

但是当我翻译成delphi代码时我遇到了问题,问题是行x = x >> 1

这是delphi代码:

function TForm1.CalculateCRC32(const data: TBytes; initial: Cardinal): Cardinal;
var
  crc: Cardinal;
  x, z: Integer;
begin
 crc := initial;

 for x in data do
 begin
    for z := 0 to 7 do
    begin
      if ((crc xor x) and $01) = 1 then
      begin
        crc := crc shr 1;
        crc := crc xor $04c11db7;
      end
      else
      begin
       crc := crc shr 1;
      end;

      x := x shr 1; // here its the problem I have
    end;
 end;
crc := crc and $ffffffff;
Result := crc;

结束;

我该如何解决这个问题? 预先感谢。

我使用的是Delphi XE11.3

为了进行测试,我这样做:

data := '123456780000000077000000';
bytedata := HexToBytes(data); //TBytes type

initDataStr := '$FFFFFFFF'; 
initData := Cardinal(StrToInt64(initDataStr));

result := CalculateCRC32(bytedata, initData); //The result should be 7085D2 in hexadecimal. 
python delphi crc32
1个回答
0
投票

你可以试试这个方法。

但是您有一些 Delphi 和 Python 循环和语法的基础知识。

function TForm1.CalculateCRC32(const data: TBytes; initial: Cardinal): Cardinal;
var
  crc, x, z: Cardinal;
begin
 crc := initial;

 for x in data do
 begin
    z := 0;
    while z < 8 do
    begin
      if ((crc xor x) and $01) = 1 then
      begin
        crc := crc shr 1;
        crc := crc xor $04c11db7;
      end
      else
      begin
        crc := crc shr 1;
      end;

      x := x shr 1; // Now it won't affect the loop variable directly
      Inc(z);
    end;
 end;
 crc := crc and $ffffffff;
 Result := crc;
end;

我只是避免通过使用 z 变量来调节按位操作来更改循环变量 x,从而确保循环按预期运行。

© www.soinside.com 2019 - 2024. All rights reserved.