Base62 Encode

If you have large integers and you want to shrink them down in size for whatever reason, you can use this code. Should be easy enough to extend if you want even higher bases (just add a few more chars and increase the base).

[cc lang=”php”]
return $str;

* Convert a number from any base to base 10
* @param string $str Number
* @param int $base Base of number. If null, will use strlen($chars) as base.
* @param string $chars Characters use in base, arranged lowest to highest. Must be at least $base characters long.
* @return int Number converted to base 10
function base_decode($str, $base=62, $chars=’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’) {
if(!isset($base)) $base = strlen($chars);
$len = strlen($str);
$val = 0;
$arr = array_flip(str_split($chars));
for($i = 0; $i < $len; ++$i) { $val = bcadd($val, bcmul($arr[$str[$i]], bcpow($base, $len-$i-1))); } return $val; } [/cc] (code updated 26-Aug-2011 for arbitrary precision using BC Math)

Posted in

6 thoughts on “Base62 Encode

  1. You’re welcome. Glad it was helpful, and nice port!


Leave a Reply

Your email address will not be published. Required fields are marked *