Search code examples
javaphpinteger-overflow

php multiply strange integer overflow behavior


In scala(java)

scala> 8218553819005469347L * 31
res75: Long = -3479248642764172867

But in php (5.5 / 64bit linux system)

<?php
echo (int)(8218553819005469347 * 31);

it prints -3479248642764177408

How to make php return same result as java.


Solution

  • function multiply31($num)  {
        return (int)(($num << 5) - $num);
    }
    

    Turn the multiply into add seems work.