I am trying to convert a base 10 number to any base by using conversion. Right now this is the code I have came up with. I have a sad feeling this may be completely wrong. The
public class Converter {
private static char symbols[] = new char[] { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T' };
public static void main ( String args[] )
{
Converter converter = new Converter ();
System.out.println( converter.convert ( 31, 16 ));
}
public String convert ( int number, int base )
{
return convert(number, base, 0, "" );
}
private String convert ( int number, int base, int position, String result )
{
if ( number < Math.pow(base, position + 1) )
{
return symbols[(number / (int)Math.pow(base, position))] + result;
}
else
{
int remainder = (number % (int)Math.pow(base, position + 1));
return convert ( number - remainder, base, position + 1, symbols[remainder / (int)( Math.pow(base, position) )] + result );
}
}
}
This will convert from Base 2 to Base 36, although you could expand it by adding more symbols.