Base62 Encode / Decode


/ Published in: PHP
Save to your folder(s)

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).


Copy this code and paste it in your HTML
  1. function encode($val, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
  2. // can't handle numbers larger than 2^31-1 = 2147483647
  3. $str = '';
  4. do {
  5. $i = $val % $base;
  6. $str = $chars[$i] . $str;
  7. $val = ($val - $i) / $base;
  8. } while($val > 0);
  9. return $str;
  10. }
  11.  
  12. function decode($str, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
  13. $len = strlen($str);
  14. $val = 0;
  15. $arr = array_flip(str_split($chars));
  16. for($i = 0; $i < $len; ++$i) {
  17. $val += $arr[$str[$i]] * pow($base, $len-$i-1);
  18. }
  19. return $val;
  20. }
  21.  
  22. echo encode(2147483647); // outputs 2lkCB1

URL: http://programanddesign.com/php/base62-encode/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.