Base62 Encode / Decode

Base62 Encode / Decode

  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. function decode($str, $base=62, $chars=‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’) {
  12. $len = strlen($str);
  13. $val = 0;
  14. $arr = array_flip(str_split($chars));
  15. for($i = 0; $i < $len; ++$i) {
  16. $val += $arr[$str[$i]] * pow($base, $len$i1);
  17. }
  18. return $val;
  19. }
  20. echo encode(2147483647); // outputs 2lkCB1

 

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s