0

Below is the left shift code in c# and php7.

Why and how to match PHP output with C# output?

Thanks in advance.

C#

    var ret = 0xFFFFFFFF;
    var a=ret << 8;
    Console.WriteLine(a);

Output

        4294967040

where as

PHP

    $ret = 0xFFFFFFFF;
    $a=$ret << 8;
    echo $a;

Output

       1099511627520
  • I'm going to guess this is because C# and PHP have different max values for the data types you're using. – gunr2171 Mar 31 '21 at 13:57
  • See [What's the maximum value for an int in PHP?](https://stackoverflow.com/questions/670662/whats-the-maximum-value-for-an-int-in-php). – gunr2171 Mar 31 '21 at 14:04

1 Answers1

1

Don't use the var keyword, use explicitly long instead of it:

long ret = 0xFFFFFFFF;
long a = ret << 8;
Console.WriteLine(a);

The var will use a 32 bit integer not a 64 bit integer.

Kapitany
  • 1,319
  • 1
  • 6
  • 10
  • The long datatype represents a 64-bit signed integer. – Kapitany Mar 31 '21 at 14:01
  • My mistake. Could you add an explanation why bit shifting a `UInt32` (which hex literals are when using `var`) produces the "wrong" result, while a long is "right"? – gunr2171 Mar 31 '21 at 14:16
  • The UInt32 value type represents unsigned integers with values ranging from 0 to 4,294,967,295. The result (1099511627520) is greater than the maximum value of an UInt32. – Kapitany Mar 31 '21 at 15:35
  • Thanks In PHP $ret = 0xFFFFFFFF; $a=($ret << 8 ) & 0xFFFFFFFF;//convet to 32 bit integer echo $a; – danishqamar Apr 01 '21 at 09:59