Skip to content
Advertisement

Python bitshifting vs PHP bitshifting

I have a code in python which uses right bit shift and it returns the correct value but the same way I tried to shift right in PHP, it returns 0.

Python code:

print((1640628245535850*0x20c49ba5e353f7cf) >> 64)
// returns 210000415428588

PHP code:

$x8 = (1640628245535850*0x20c49ba5e353f7cf);
$x8 = number_format($x8, 0, '', '');
echo $x8 >> 64;
// returns 0

I have a very little experience in maths functions, would be great if someone can help.

Advertisement

Answer

This operator >> is working on an integer value, so the left side of the operator will convert to an integer.

Based on the manual, the max value of the integer is about 9E18. https://www.php.net/manual/en/language.types.integer.php

While the first part of calculation (1640628245535850*0x20c49ba5e353f7cf) is about 4E33. So it’s clear that PHP can not do this calculation in integer mode. Fortunately, PHP automatically does the calculation in the Floating Point mode.

But the problem starts where >> is used. PHP tries to convert ~4E33 to integer and overflow will happen.

Solution is doing calculation in Floating Point. In math, 1-bit shift to the right is equal to divide by 2. So this code return true value:

echo 1640628245535850 * 0x20c49ba5e353f7cf / pow(2,64);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement