Last active
December 14, 2015 21:49
-
-
Save jmc734/5153951 to your computer and use it in GitHub Desktop.
Get the 32-bit CRC code for a string in base 62 (0-9A-Za-z)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get the 32-bit CRC code for a string in base 62 | |
* | |
* @param string $str The string to get the CRC for | |
* @param array $chars Optional. An array mapping the integer keys 0-61 to distinct characters. | |
* If not supplied, the character for each value will be calculated on the fly. | |
* @return string The base 62 CRC code | |
*/ | |
function str_crc62($str, $chars = null){ | |
// Get the CRC code for the string | |
$crc = intval(sprintf('%u', crc32($str))); | |
$crc62 = ''; | |
// Convert CRC from base 10 to base 62 (0-9A-Za-z) | |
do{ | |
// Get the mod of the current CRC | |
$m = $crc%62; | |
// Convert the mod value to a character and add it to the | |
if($chars !== null) | |
$crc62 = $chars[$m].$crc62; | |
else | |
$crc62 = chr((($m>35)?61:(($m>9)?55:48))+$m).$crc62; | |
// Set the CRC to the integer division value | |
$crc = ($crc-$m)/62; | |
} while($crc > 0); | |
return $crc62; | |
} | |
// Generate the character map | |
$chars = array(); | |
for($m = 0; $m < 62; $m++){ | |
$chars[$m] = chr((($m>35)?61:(($m>9)?55:48))+$m); | |
} | |
// Both should return '2ygOVa' | |
str_crc62('*_TeSt.StRiNg_*', $chars); | |
str_crc62('*_TeSt.StRiNg_*'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment