Created
October 5, 2016 12:56
-
-
Save shmaltorhbooks/e5802107b6c88f42233313a2640c4f39 to your computer and use it in GitHub Desktop.
convert id between number systems
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
class NumberSystem | |
{ | |
const DEFAULT_ALPHABET = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'; | |
public static function baseEncode($num, $alphabet = self::DEFAULT_ALPHABET) { | |
$baseCount = strlen($alphabet); | |
$encoded = ''; | |
while ($num >= $baseCount) { | |
$div = $num/$baseCount; | |
$mod = ($num-($baseCount* (int) $div)); | |
$encoded = $alphabet[$mod] . $encoded; | |
$num = (int) $div; | |
} | |
if ($num) { | |
$encoded = $alphabet[$num] . $encoded; | |
} | |
return $encoded; | |
} | |
public static function baseDecode($num, $alphabet = self::DEFAULT_ALPHABET) { | |
$decoded = 0; | |
$multi = 1; | |
while (strlen($num) > 0) { | |
$digit = $num[strlen($num)-1]; | |
$decoded += $multi * strpos($alphabet, $digit); | |
$multi = $multi * strlen($alphabet); | |
$num = substr($num, 0, -1); | |
} | |
return $decoded; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment