我对此进行了相当广泛的搜索,但没有找到任何东西。问题是:把一个以10为基数的数转换成一个非常大的基数,比如以400为基数。
这样做的目的仅仅是教育。
我知道没有足够的ASCII字符来表示以400为基数的400个不同的"数字",但对于这个问题,高基数的每个位值可以保持以10为基数。为了便于阅读,高基数的每个位值可以用空格(或句点)分隔。
以400为基数的数字示例:
372 0 105 50
基数500的例子:
492.0.256
以1000为基数的数字示例(这是一个以1000为基数的5位数字):
854 685 353 498 123
非常感谢任何帮助。也欢迎提出表示或分隔数字的替代方法。
假设$number
为源数,$base
为目标基数,我们使用循环执行基数转换,其中每次迭代:
- 取模
$number % $base
的余数。返回当前数字的值为$digit
。 -
$number
减去$digit
。这将在后面给我们四舍五入划分。 -
$number
除以$base
。我们将计算提升到下一位数字。 - 我们存储
$digit
. - 返回步骤1,直到
$number
等于0
。
例子:
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
本程序的代码形式,使用BCMath任意精度数学:
// 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));
}
测试:echo largeBaseConvert('1234567', '17');
输出14 13 4 14 10
检查:
14 * 17^4 = 1169294
13 * 17^3 = 63869
4 * 17^2 = 1156
14 * 17^1 = 238
10 * 17^0 = 10
= 1234567