Skip to content

Instantly share code, notes, and snippets.

@mattparlane
Created January 31, 2018 13:42
Show Gist options
  • Save mattparlane/6b2b63aec32470b3b5ed27696e398f77 to your computer and use it in GitHub Desktop.
Save mattparlane/6b2b63aec32470b3b5ed27696e398f77 to your computer and use it in GitHub Desktop.
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