Skip to content

Instantly share code, notes, and snippets.

@ethaizone
Created May 17, 2016 11:05
Show Gist options
  • Save ethaizone/c955b09bf10ff4659d73fa9fb88c7865 to your computer and use it in GitHub Desktop.
Save ethaizone/c955b09bf10ff4659d73fa9fb88c7865 to your computer and use it in GitHub Desktop.
Custom base number converter.
<?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