Last active
April 12, 2021 11:33
-
-
Save ProjectOrangeBox/28ef355fc9953c756c70e2c223376259 to your computer and use it in GitHub Desktop.
base 62 encode / decode
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
function base62_encode($num) { | |
$b = 62; | |
$base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
$r = $num % $b ; | |
$res = $base[$r]; | |
$q = floor($num/$b); | |
while ($q) { | |
$r = $q % $b; | |
$q = floor($q/$b); | |
$res = $base[$r].$res; | |
} | |
return $res; | |
} | |
function base62_decode( $num) { | |
$b = 62; | |
$base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
$limit = strlen($num); | |
$res = strpos($base,$num[0]); | |
for($i=1;$i<$limit;$i++) { | |
$res = $b * $res + strpos($base,$num[$i]); | |
} | |
return $res; | |
} | |
echo base62_encode(68).PHP_EOL; | |
echo base62_decode('ghYU45').PHP_EOL; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment