neuronich
neuronich

Reputation: 135

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

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!

Upvotes: 9

Views: 4236

Answers (1)

RiaD
RiaD

Reputation: 47640

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

Try use BCMath instead for big numbers

Upvotes: 9

Related Questions