Skip to content

Instantly share code, notes, and snippets.

@ProjectOrangeBox
Last active April 12, 2021 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProjectOrangeBox/28ef355fc9953c756c70e2c223376259 to your computer and use it in GitHub Desktop.
Save ProjectOrangeBox/28ef355fc9953c756c70e2c223376259 to your computer and use it in GitHub Desktop.
base 62 encode / decode
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