Program to convert base m number to base n number


#1

you are given a base m number, write a program to convert it into base n number.


#2

You can do it in two steps, first convert base m number to base 10. Then convert this base 10 num to base n.

private int getValue(char c)
{
    if (c >= '0' && c <= '9')
        return (int)c - '0';
    else
        return (int)c - 'A' + 10;
}

private char getChar(int num)
{
    if (num >= 0 && num <= 9)
        return (char)(num + '0');
    else
        return (char)(num - 10 + 'A');
}

private long convertBase10(String input, int m)
{
	long a = 0;
	for(int i = 0; i < input.length(); ++i)
	{
		a += getValue(input.charAt(i));
		a *= m;
	}
	return a;
}

public String convert(String inputNum, int m, int n)
{
	long a = convertBase10(inputNum, m);
	String output = "";
	while(a > 0)
	{
		output += getChar(a % n);
		a /= n;
	}
	return output.reverse();
}