Created
December 24, 2014 14:42
-
-
Save jankuo/e9ecb22b0134f720265f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<?php | |
class Hex62 | |
{ | |
const base = 62; | |
const letters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
public static function decode( $str ) | |
{ | |
$ret = 0; | |
$len = strlen($str) - 1; | |
for( $t = 0; $t <= $len; $t++ ) | |
{ | |
$ret += strpos(self::letters, substr($str, $t, 1)) * pow(self::base, $len - $t); | |
} | |
return $ret; | |
} | |
public static function encode ( $number ) | |
{ | |
$ret = ''; | |
for($t = floor(log10($number) / log10(self::base)); $t >= 0; $t-- ) | |
{ | |
$a = floor($number / pow(self::base, $t)); | |
$ret .= substr(self::letters, $a, 1); | |
$number -= $a * pow(self::base, $t); | |
} | |
return $ret; | |
} | |
} | |
if ( isset($argv[1]) ) | |
{ | |
$number = $argv[1]; | |
echo "number:",$number,"\n"; | |
echo $str = Hex62::encode($number),"\n"; | |
echo Hex62::decode( $str ),"\n"; | |
echo $number == Hex62::decode( $str ) ? "true" : "false","\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment