PHP bitwise left shifting 32 spaces problem and bad results with large numbers arithmetic operations
bit-manipulation, php, precision
Solution
Based on Pascal MARTIN's suggestions, i tried both the BCMath and the GMP extension and came up with the following solutions:
With BCMath:
$a = 516103988;
$s = bcpow(2, 32);
$a = bcadd(bcmul($a, $s), 9379);
echo $a; // works, echoes 2216649749795185827
With 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
From what i understand, there is a far greater chance for BCMath to be installed on the server then GMP, so i will be using the first solution.
Thanks :)
Problem
I have the following problems: First: I am trying to do a 32-spaces bitwise left shift on a large number, and for some reason the number is always returned as-is. For example: ``` echo(516103988<<32); // echoes 516103988 ``` Because shifting the bits to the left one space is the equivalent of multiplying by 2, i tried multiplying the number by 2^32, and it works, it returns 2216649749795176448. Second: I have to add 9379 to the number from the above point: ``` printf('%0.0f', 2216649749795176448 + 9379); // prints 2216649749795185920 ``` Should print: 2216649749795185827