note 109662 modified in function.crc32 by danbrown

From: Date: Fri, 10 Aug 2012 16:11:30 +0000
Subject: note 109662 modified in function.crc32 by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-189999@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.&#13;&#10;&#13;&#10;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. --was-- 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. http://php.net/manual/en/function.crc32.php

« previous php.notes (#189999) next »