Home > other >  Python bitshifting vs PHP bitshifting
Python bitshifting vs PHP bitshifting

Time:12-28

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.

CodePudding user response:

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);

CodePudding user response:

When running that PHP code in version 8.1.1 (with warnings enabled), I get this warning:

Deprecated: Implicit conversion from float-string "3873823918783864565866509837008896" to int loses precision

This explains it. Unlike Python, PHP's integers are not big integers, and so when they don't fit in a word (platform dependent), they are represented as floating point numbers (like here). This means precision is lost, and the output you get for bit shifting is not based on the same number as in the Python script.

If you want to have support for big integers in PHP, you could look into an extension, like GMP.

  • Related