Search code examples
c#delphidelphi-7

Delphi 7 vs C# expression evaluation


I have a Delphi-7 expression as below, all variables are of type longint-

cy:=((s1 and s2)or((s1 or s2)and not res))shr 31;

And in C# the expression is, all variables are of type int-

cy = ((s1 & s2) | ((s1 | s2) & (~res)))>>31;

where

s1  = -659459908
s2  =  283372503 
res =  217426595

When Delphi 7 evaluates it, and I look the value of expression to the right by quick watch it shows value as -1, but when I ShowMessage(IntToStr(cy)), it shows 1.

Whereas C# still shows -1.

I am working on Windows-10 64 bit system and compiling the code for Any CPU from VS2013. I tried declaring the C# variables as Int32 as well, but same phenomenon occurs.

Can anyone tell about this phenomenon, what we say this and how to proceed further.


Solution

  • In C# >> operation preserves the leftmost bit when opertaing with signed integers like int, long (alas C# doesn't have any >>> operation as in Java), when Delphi's shr doesn't:

    In both cases (C# and Delphi) we have the same evaluation for the inner formula

    // -79459485 (decimal) == 11010000101000110111000111011100 (binary) 
    ((s1 & s2) | ((s1 | s2) & (~res))) == -794594852 
    

    The final step (-794594852 >> 31 and -794594852 shr 31) is different:

    11010000101000110111000111011100 >> 31 == 11111111111111111111111111111111 (C#)
    11010000101000110111000111011100 >> 31 == 00000000000000000000000000000001 (Delphi)
    

    Amendment (let C# mimic Delphi):

     unchecked { 
       cy = (int)((uint)((s1 & s2) | ((s1 | s2) & (~res))) >> 31);
     }