Skip to content

Instantly share code, notes, and snippets.

@keiya
Last active December 12, 2015 05:18
Show Gist options
  • Select an option

  • Save keiya/4720338 to your computer and use it in GitHub Desktop.

Select an option

Save keiya/4720338 to your computer and use it in GitHub Desktop.
Decimal to/from BASE 62. 10進数⇔62進数コンバータ for PHP decodeが遅そう
<?php
/* base62.php
* by Keiya Chinen. Licensed under Creative Commons BY 3.0
* ( http://creativecommons.org/licenses/by/3.0/deed.en )
*/
// test script
//test();
//example
example(12345);
function example($n) {
$b62 = Base62::b62_encode($n);
$dec = Base62::b62_decode($b62);
echo "$n --> $b62 --> $dec\n";
}
function test() {
for ($i=10000000;$i<1000000000;++$i) {
$b62 = Base62::b62_encode($i);
$dec = Base62::b62_decode($b62);
if ($i === $dec) {
}
else {
echo 'x';
}
}
}
class Base62 {
const RADIX = 62;
static $decmap = array(
'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
);
public function b62_encode($num) {
$result = '';
while ($num > 0) {
$result = self::$decmap[$num % self::RADIX] . $result;
$num = intval($num / self::RADIX);
}
return $result;
}
public function b62_decode($str) {
$length = strlen($str);
$result = 0;
for ($i = 0; $i < $length; ++$i) {
$decval = array_search($str[$i],self::$decmap);
$result += $decval * pow(self::RADIX,$length-$i-1);
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment