Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php % (mod function) goes to negative on large numbers. How to get rid of it?

Tags:

php

How do I use % properly not to get negative result?

<?php 
    $x = 1103515246*12345;
    echo $x." ".decbin($x)."</BR>";
    $y = $x % (1 << 15);
    echo $y." ".decbin($y)."</BR>";
?>

Output:

13622895711870      11010011110111000001011001111110

-27010              11111111111111111001011001111110

RESOLVED

$y = bcmod($x,(1 << 15)); Solves the issue. Thank you for quick help! It was my first question!

like image 855
neuronich Avatar asked Aug 16 '12 19:08

neuronich


1 Answers

problem is that $x not integer but float and casted to negative int when you use %

Try use BCMath instead for big numbers

like image 134
RiaD Avatar answered Nov 15 '22 17:11

RiaD