note 109662 added to function.crc32
| From: | Clifforddotctatgmaildotcom | Date: | Tue, 07 Aug 2012 08:54:40 +0000 |
| Subject: | note 109662 added to function.crc32 | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-189940@lists.php.net to get a copy of this message | ||
The crc32() function can return a signed integer in certain environments. Assuming that it will
always return an unsigned integer 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 outcomes.
<?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:
Depending on your desired behavior, you should probably use sprintf() on the result or the generic
hash() instead. Also note that integer arithmetic operators do not have the precision to work
correctly with the integer output.
----
Server IP: 69.147.83.197
Probable Submitter: 220.255.2.158
----
Manual Page -- http://www.php.net/manual/en/function.crc32.php
Edit -- https://master.php.net/note/edit/109662
Del: integrated -- https://master.php.net/note/delete/109662/integrated
Del: useless -- https://master.php.net/note/delete/109662/useless
Del: bad code -- https://master.php.net/note/delete/109662/bad+code
Del: spam -- https://master.php.net/note/delete/109662/spam
Del: non-english -- https://master.php.net/note/delete/109662/non-english
Del: in docs -- https://master.php.net/note/delete/109662/in+docs
Del: other reasons-- https://master.php.net/note/delete/109662
Reject -- https://master.php.net/note/reject/109662
Search -- https://master.php.net/manage/user-notes.php