note 109663 added to language.operators.arithmetic
| From: | Clifforddotctatgmaildotcom | Date: | Tue, 07 Aug 2012 09:01:04 +0000 |
| Subject: | note 109663 added to language.operators.arithmetic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-189941@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 69.147.83.197
Probable Submitter: 220.255.2.131
----
Manual Page -- http://www.php.net/manual/en/language.operators.arithmetic.php
Edit -- https://master.php.net/note/edit/109663
Del: integrated -- https://master.php.net/note/delete/109663/integrated
Del: useless -- https://master.php.net/note/delete/109663/useless
Del: bad code -- https://master.php.net/note/delete/109663/bad+code
Del: spam -- https://master.php.net/note/delete/109663/spam
Del: non-english -- https://master.php.net/note/delete/109663/non-english
Del: in docs -- https://master.php.net/note/delete/109663/in+docs
Del: other reasons-- https://master.php.net/note/delete/109663
Reject -- https://master.php.net/note/reject/109663
Search -- https://master.php.net/manage/user-notes.php