在 C 中将一个数字从一个基数转换为另一个基数
#include
long convertInBase10 (long n, int base)
{
long quotient = n / 10;
余数 = n % 10;
if (quotient == 0)
return 保持不变;
else
return convertingBase10 (quotient, base) * base + remainder;
}
long convertEnBase2 (long n, int base)
{
long quotient = n / 2;
余数 = n % 2;
if (quotient == 0)
return 保持不变;
else
return convertEnBase2 (quotient, base) * base + remainder;
}
long convertInBase4 (long n, int base)
{
long quotient = n / 4;
余数 = n % 4;
if (quotient == 0)
return 保持不变;
else
return convertenBase4 (quotient, base) * base + 余数;
}
long convertInBase8 (long n, int base)
{
long quotient = n / 8;
长余数 = n % 8;
if (quotient == 0)
return 保持不变;
else
return convertenBase8 (quotient, base) * base + remainder;
}
long convertInBase16 (long n, int base)
{
long quotient = n / 16;
长余数 = n % 16;
if (quotient == 0)
return 保持不变;
else
return convertingBase16 (quotient, base) * base + remainder;
}
int main() {
long n = 17;
int base = 10;
//十进制 -->base(2,4,8,16)
printf (%ld to base %2d = %ld to base 2\n”,n, base, convert to Base2 (n, base);
printf (%ld to base %2d = %ld to base 4\n”,n, base, convert to Base4 (n, base);
printf (%ld to base %2d = %ld to base 8\n”,n, base, convert to Base8 (n, base) );
printf (%ld to base %2d = %ld to base 16\n”,n, base, convert toBase16 (n, base);
//二进制 -->十进制
n = 1010;
= 2;
printf (%ld to base %2d = %ld to base 10\n”,n, base, convert to Base10 (n, base);
//十六进制 -->十进制
n = 124;
= 16;
printf (%ld to base %2d = %ld to base 10\n”,n, base, convert to Base10 (n, base);
//base 8 -->二进制
n = 12;
= 8;
printf (%ld to base %2d = %ld to base 10\n”,n, base, convert to Base10 (n, base);
返回 0;
}