Last active
December 28, 2015 00:39
-
-
Save tcz/7414872 to your computer and use it in GitHub Desktop.
Convert from any base to any base in PHP
This file contains hidden or 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 | |
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