PHP bitwise left shift 32-bit problem and poor results with arithmetic operations of large numbers

I have the following problems:

Firstly: I'm trying to perform a bitwise offset of 32 spaces for a large number, and for some reason, the number always returns as is. For instance:

echo(516103988<<32); // echoes 516103988

Since shifting bits to the left of one space is equivalent to multiplying by 2, I tried to multiply the number by 2 ^ 32, and it works, it returns 2216649749795176448.

Secondly: I have to add 9379 to the number from the above paragraph:

printf('%0.0f', 2216649749795176448 + 9379); // prints 2216649749795185920 

Must Type: 2216649749795185827

+3
source share
3 answers

Pascal MARTIN, BCMath, GMP :

BCMath:

$a = 516103988;
$s = bcpow(2, 32);    
$a = bcadd(bcmul($a, $s), 9379);
echo $a; // works, echoes 2216649749795185827

GMP:

$a = gmp_init(516103988); 
$s = gmp_pow(gmp_init(2), 32); 
$a = gmp_add(gmp_mul($a, $s), gmp_init(9379)); 
echo gmp_strval($a);  // also works

, , , BCMath , GMP, .

:)

+4

32 , , , , , , 32 .

:

32 32 .
, 32 . gmp PHP_INT_MAX.

+4

The integer accuracy of Php is limited by the size of the machine word (32, 64). To work with integer integers, you must store them as strings and use bc or gmp library:

   echo bcmul('516103988', bcpow(2, 32));  // 2216649749795176448
+4
source

Source: https://habr.com/ru/post/1737323/


All Articles