我正在将一些 C# 代码移植到 Delphi (XE5)。 C# 代码有这样的代码:
long t = ...
...
t = (t >> 25) + ...
我把它翻译成
t: int64;
...
t := (t shr 25) + ...
现在我看到 Delphi(有时)计算出错误的值来移动负 t,例如:
-170358640930559629 shr 25
Windows Calculator: -5077083139
C# code: -5077083139
Delphi:
-170358640930559629 shr 25 = 544678730749 (wrong)
对于此示例,-1*((-t shr 25)+1) 在 Delphi 中给出正确的值。
对于 t 的其他负值,简单的类型转换为整数似乎给出了正确的结果:
integer(t shr 25)
我在二进制运算和表示方面处于极限,因此如果您能够帮助我在 Delphi 中获得与 C# 和 Windows 计算器相同的结果,我将不胜感激。
最佳答案
基于article链接在 Filipe 的 answer (其中说明了 Delphi 执行 shr
而不是其他人执行 sar
的原因),这是我对此的看法:
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;
关于delphi - int64 上的 SHR 未返回预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21940986/