Skip to content

Instantly share code, notes, and snippets.

@shmaltorhbooks
Created October 5, 2016 12:56
Show Gist options
  • Save shmaltorhbooks/e5802107b6c88f42233313a2640c4f39 to your computer and use it in GitHub Desktop.
Save shmaltorhbooks/e5802107b6c88f42233313a2640c4f39 to your computer and use it in GitHub Desktop.
convert id between number systems
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