Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Integer -> Alphabet encoder: https://stackoverflow.com/questions/22043451
class AlphabetEncoder {
private static $ALPHABET;
private static $ENCODE_LENGTH;
private static function populateAlphabet() {
if (self::$ENCODE_LENGTH) return;
for ($n = 48; $n < 58; $n++)
self::$ALPHABET[] = chr($n);
for ($n = 65; $n < 91; $n++)
self::$ALPHABET[] = chr($n);
for ($n = 97; $n < 123; $n++)
self::$ALPHABET[] = chr($n);
self::$ENCODE_LENGTH = count(self::$ALPHABET);
}
public static function encode($victim) {
self::populateAlphabet();
$list = [];
do {
$list[] = self::$ALPHABET[$victim % self::$ENCODE_LENGTH];
$victim = floor($victim / self::$ENCODE_LENGTH);
} while ($victim > 0);
$list = array_reverse($list);
return implode('', $list);
}
public static function decode($encoded) {
self::populateAlphabet();
$ret = 0;
$c = '';
for ($index = 0; $index < strlen($encoded); $index++) {
$c = substr($encoded, $index, 1);
$ret *= self::$ENCODE_LENGTH;
$ret += array_search($c, self::$ALPHABET);
}
return $ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.