Skip to content

Instantly share code, notes, and snippets.

@tcz
Last active December 28, 2015 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcz/7414872 to your computer and use it in GitHub Desktop.
Save tcz/7414872 to your computer and use it in GitHub Desktop.
Convert from any base to any base in PHP
<?php
function convertBases($number, $from_digits, $to_digits)
{
$from_digits = str_split($from_digits, 1);
$to_digits = str_split($to_digits, 1);
$number = str_split($number, 1);
$number_dec = "0";
$ord = 0;
while(count($number))
{
$digit = array_search(array_pop($number), $from_digits);
$digit_value = bcmul($digit, bcpow(count($from_digits), $ord));
$number_dec = bcadd($number_dec, $digit_value);
$ord++;
}
$result_digits = array();
do {
$result_digits[] = bcmod($number_dec, count($to_digits));
$number_dec = bcdiv($number_dec, count($to_digits), 0);
} while($number_dec !== "0");
$result = "";
while(count($result_digits))
{
$result .= $to_digits[array_pop($result_digits)];
}
return $result;
}
echo convertBases( "FF", "0123456789ABCDEF", "0123456789" ), "\n";
// Prints 255
echo convertBases( "255", "0123456789", "0123456789ABCDEF" ), "\n";
// Prints FF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment