note 109663 deleted from language.operators.arithmetic by danbrown
| From: | danbrown@php.net | Date: | Fri, 10 Aug 2012 16:11:51 +0000 |
| Subject: | note 109663 deleted from language.operators.arithmetic by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-190000@lists.php.net to get a copy of this message | ||
Note Submitter: Clifford dot ct at gmail dot com
----
Certain functions eg. crc32() can return an integer value outside the range of precision handled by
an integer arithmetic operator.
Making the assumption that any operator has arbitrary precision is not portable.
I created a sample code here and ran it off a random virtual server. Do note the output may vary
according to your environment but it is sufficient to illustrate the possible gotchas.
<?php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
$divisor = 256;
$a = $checksum;
echo "Original crc32 output a = $a, to divide by $divisor\n";
$r = $a % $divisor;
echo "% operator: r = $r \n";
$r = intval(fmod($a, $divisor));
echo "fmod function: r = $r \n";
$r = bcmod($a, $divisor);
echo "bcmod function: r = $r \n";
echo "\n";
$a = sprintf("%u", $checksum);
echo "sprintf crc32 output a = $a, to divide by $divisor\n";
$r = $a % $divisor;
echo "% operator: r = $r \n";
$r = intval(fmod($a, $divisor));
echo "fmod function: r = $r \n";
$r = bcmod($a, $divisor);
echo "bcmod function: r = $r \n";
?>
Output:
Original crc32 output a = -2103228862, to divide by 256
% operator: r = -190
fmod function: r = -190
bcmod function: r = -190
sprintf crc32 output a = 2191738434, to divide by 256
% operator: r = 255
fmod function: r = 66
bcmod function: r = 66
Conclusion:
Note that integer arithmetic operators do not have the precision to work correctly in some
applications.