Convert a number from one base to another base in C
#include < stdio .h="">
long convertInBase10 (long n, int base)
{
long quotient = n / 10;
remainder = n % 10;
if (quotient == 0)
return remains;
else
return convertingBase10 (quotient, base) * base + remainder;
}
long convertEnBase2 (long n, int base)
{
long quotient = n / 2;
remainder = n % 2;
if (quotient == 0)
return remains;
else
return convertEnBase2 (quotient, base) * base + remainder;
}
long convertInBase4 (long n, int base)
{
long quotient = n / 4;
remainder = n % 4;
if (quotient == 0)
return remains;
else
return convertenBase4 (quotient, base) * base + remainder;
}
long convertInBase8 (long n, int base)
{
long quotient = n / 8;
long remainder = n % 8;
if (quotient == 0)
return remains;
else
return convertenBase8 (quotient, base) * base + remainder;
}
long convertInBase16 (long n, int base)
{
long quotient = n / 16;
long remainder = n % 16;
if (quotient == 0)
return remains;
else
return convertingBase16 (quotient, base) * base + remainder;
}
int main() {
long n = 17;
int base = 10;
//Decimal --> 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);
//Binary --> Decimal
n = 1010;
= 2;
printf ("%ld to base %2d = %ld to base 10\n",n, base, convert to Base10 (n, base);
//hexadecimal --> Decimal
n = 124;
= 16;
printf ("%ld to base %2d = %ld to base 10\n",n, base, convert to Base10 (n, base);
//base 8 --> binary
n = 12;
= 8;
printf ("%ld to base %2d = %ld to base 10\n",n, base, convert to Base10 (n, base);
return 0;
}