Assuming $number
as source number and $base
as target base, we perform base conversion using a loop, where for each iteration:
- Get the remainder of the modulo
$number % $base
. This returns the value of the current digit as $digit
.
- Subtract
$digit
from $number
. This will give us rounded divisions later on.
- Divide
$number
by $base
. We elevate the calculation to the next digit.
- We store
$digit
.
- Back to step 1 until
$number
is equal to 0
.
Examples:
Step 1 2 3 4
D=N%B N=N-D N=N/B D
-----------------------------------------
512 in base 10 = 512
-----------------------------------------
512 2 510 51 2
51 1 50 5 1
5 5 0 0 5
-----------------------------------------
27 in base 2 = 11011
-----------------------------------------
27 1 26 13 1
13 1 12 6 1
6 0 6 3 0
3 1 2 1 1
1 1 0 0 1
-----------------------------------------
1234567 in base 400 = 7 286 167
-----------------------------------------
123456 167 1234400 3086 167
3086 286 2800 7 286
7 7 0 0 7
This procedure in code form, using BCMath Arbitrary Precision Mathematics:
// arguments must be strings
function largeBaseConvert($num, $base) {
$output = array();
while($num !== '0') {
// get remainder from modulo
$digit = bcmod($num, $base);
// substract remainder from number
$num = bcsub($num, $digit);
// divide by base
$num = bcdiv($num, $base);
// save
$output[] = $digit;
}
// need to reverse the array as we count from the lowest digit
return implode(' ', array_reverse($output));
}
Test:
echo largeBaseConvert('1234567', '17');
Output
14 13 4 14 10
Check:
14 * 17^4 = 1169294
13 * 17^3 = 63869
4 * 17^2 = 1156
14 * 17^1 = 238
10 * 17^0 = 10
= 1234567