Created
May 17, 2016 11:05
-
-
Save ethaizone/c955b09bf10ff4659d73fa9fb88c7865 to your computer and use it in GitHub Desktop.
Custom base number converter.
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
<?php | |
/** | |
* Code demo for convert base number with custom base character map. | |
* Not support negative number. | |
*/ | |
// base from toHex on http://hashids.org/ | |
function intToChar($input) | |
{ | |
$hash = ""; | |
$alphabet = BASE_CHARACTER; | |
$alphabetLength = strlen($alphabet); | |
do { | |
$hash = $alphabet[$input % $alphabetLength] . $hash; | |
$input = intval($input / $alphabetLength, 10); | |
} while ($input); | |
return $hash; | |
} | |
// My func that will decode it back. | |
// I write via reverse logic from upper function. | |
// @author Nimit Suwannagate <ethaizone@hotmail.com> | |
function charToInt($input) | |
{ | |
$dex = 0; | |
$alphabet = BASE_CHARACTER; | |
$alphabetLength = strlen($alphabet); | |
$input = str_split($input); | |
do { | |
$multiple = count($input)-1; | |
$char = array_shift($input); | |
$index = strpos($alphabet, $char); | |
$dex += pow($alphabetLength, $multiple)*$index; | |
} while ($input); | |
return $dex; | |
} | |
define('BASE_CHARACTER', "fedcba9876543210"); | |
$number = 500; | |
$char = intToChar($number); | |
$decoded = charToInt($char); | |
echo "Number: " . $number .PHP_EOL; | |
echo "Char: " . $char .PHP_EOL; | |
echo "Decode: " . $decoded .PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment