SHR on int64 does not return the expected result

I am porting some C # code to Delphi (XE5). C # code has this code:

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

I translated it to

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

Now I see that Delphi (sometimes) calculates the wrong values ​​to offset negative t, for example:

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

Delphi: 
-170358640930559629 shr 25               = 544678730749 (wrong)

In this example, -1 * ((- t shr 25) +1) gives the correct value in Delphi.

For other negative values ​​of t, a simple example method for integers gives the correct result:

integer(t shr 25)

I am in my restriction regarding binary operations and representations, so I would appreciate any help just by getting the same results in Delphi as in C # and the Windows calculator.

+3
source share
2 answers

, Filipe answer ( , Delphi shr, , a 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;
+4

, , C Delphi Shr, . , C β†’ , . , , , . :

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

, !

0

All Articles