C Language Convert Number Bases

2.1k Views Asked by At

I need a program that: Can convert any number in a specific base and convert it in another base. It must work for real numbers (e.g 7.34 , 3.14, etc.)

Input: number1, base1, base_to_which_it_must_be_converted Output: Converted number:

I managed to write such programs, but they wont work for real numbers.

#include <stdio.h>
#include <string.h>
char reVal(int num)
{
    if (num >= 0 && num <= 9)
        return (char)(num + '0');
    else
        return (char)(num - 10 + 'A');
}


void strev(char *str)
{
    int len = strlen(str);
    int i;
    for (i = 0; i < len/2; i++)
    {
        char temp = str[i];
        str[i] = str[len-i-1];
        str[len-i-1] = temp;
    }
}


char* fromDeci(char res[], int base, int inputNum)
{
    int index = 0;


    while (inputNum > 0)
    {
        res[index++] = reVal(inputNum % base);
        inputNum /= base;
    }
    res[index] = '\0';


    strev(res);

    return res;
}


int main()
{
    int inputNum = 10, base = 3;
    char res[100];
    printf("Equivalent of %d in base %d is "
           " %s\n", inputNum, base, fromDeci(res, base, inputNum));
    return 0;
}

#include <stdlib.h>
#include <stdio.h>
int b,c,x,nr,nr2;
char z;

int main()
{
    int num,i,l,b,a[50];
    l=0;
printf("introduce the number and its base\n");
scanf("%d",&num);
scanf("%d",&b);
  int n;
i=0;
n=num;
l=0;
while (n!=0)
   {
       l++;
       n/=10;
   }
   n=num;
   i=l;
   while (n!=0)
   {
       a[i]= n%10;
       n/=10;
       i--;
   }
   i=0;
while(i<=l)
    {
x=x*b+a[i];
i++;
    }
    printf("\n%d",x);
return 0;
}
2

There are 2 best solutions below

0
On

First of all, as you are taking real numbers you need to change the type of num. It should be "float num;"

and if you want to convert 3.14 from decimal to binary then you need to break it into two part, one is the 3 and another one is 0.14 then convert these two separately in the base you like and then add them up.

See this

hope this helps

0
On

Our number system is called base 10 with positional notattion. It means that number 123 means 1*10^2 + 2*10^1 + 3*10^0 = 100 + 20 +3. You can adapt this for any base.

You need digits that cover your base, so base 36 means digits 0..9, a..z (36 digits) and then adapt the above formula.

The formula would be, more generic: a*base^n + b*base^(n-1) + ... q*base^0, with n the number of digits in the number.

For floating point it works the same, but after the decimal point you get negative exponents.

To convert from and to any base, first convert to a common base, and then convert to the 'to' base.