Created
February 9, 2015 07:08
-
-
Save MNBuyskih/f7780fc82de7dafdcd21 to your computer and use it in GitHub Desktop.
php to base 62 - from base 62
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* src - http://stackoverflow.com/questions/4964197/converting-a-number-base-10-to-base-62-a-za-z0-9 | |
*/ | |
class Base62 { | |
public static $table = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
public static function encode($num) { | |
$base = 62; | |
$table = self::$table; | |
$rest = $num % $base; | |
$return = $table[$rest]; | |
$floor = floor($num / $base); | |
while ($floor) { | |
$rest = $floor % $base; | |
$floor = floor($floor / $base); | |
$return = $table[$rest] . $return; | |
} | |
return $return; | |
} | |
public static function decode($num) { | |
$base = 62; | |
$table = self::$table; | |
$limit = strlen($num); | |
$res = strpos($table, $num[0]); | |
for ($i = 1; $i < $limit; $i++) { | |
$res = $base * $res + strpos($table, $num[$i]); | |
} | |
return $res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment