3

我正在将一些 C# 代码移植到 Delphi (XE5)。C# 代码有这样的代码:

long t = ...
...                
t = (t >> 25) + ...

我把它翻译成

t: int64;
...
t := (t shr 25) + ...

现在我看到德尔福(有时)计算错误的值来移动负 t,例如:

-170358640930559629 shr 25
Windows Calculator: -5077083139
C# code: -5077083139

Delphi: 
-170358640930559629 shr 25               = 544678730749 (wrong)

对于这个例子,-1*((-t shr 25)+1) 在 Delphi 中给出了正确的值。

对于 ta 的其他负值,简单类型转换为整数似乎给出了正确的结果:

integer(t shr 25)

我在二进制操作和表示方面处于极限,所以如果能在 Delphi 中获得与 C# 和 Windows 计算器中相同的结果,我将不胜感激。

4

2 回答 2

4

根据Filipe 的回答中链接的文章(其中说明了 Delphi 执行 a而不是其他人执行 a 的原因),这是我对此的看法:shrsar

function CalculatorRsh(Value: Int64; ShiftBits: Integer): Int64;
begin
  Result := Value shr ShiftBits;
  if (Value and $8000000000000000) > 0 then
    Result := Result or ($FFFFFFFFFFFFFFFF shl (64 - ShiftBits));
end;
于 2014-02-21T20:16:32.313 回答
0

正如你在这里所读到的,C 和 Delphi 对待 Shr 的方式是不同的。不是指指点点,但 C 的 >> 并不是真正的 shr,它实际上是 sar。无论如何,我发现的唯一解决方法是手动进行数学运算。这是一个例子:

function SAR(a, b : int64): int64;
begin
  result := round(a / (1 shl b));
end;

希望能帮助到你!

于 2014-02-21T18:19:33.897 回答