Created
January 31, 2018 13:42
-
-
Save mattparlane/6b2b63aec32470b3b5ed27696e398f77 to your computer and use it in GitHub Desktop.
Integer -> Alphabet encoder: https://stackoverflow.com/questions/22043451
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 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