I have a professor that does not allow me to use the easy method to convert a decimal to other bases (binary, hex, and octal). I have to create my own method to do so.
public static String base(int num, int base)
{
String output = "";
while (num != 0)
{
int value = num % base;
output = getDigit(value) + output;
num = num / base;
}
return output;
}
public static char getDigit(char n)
{
{
switch (n)
{
case 0: return '0';
case 1: return '1';
case 2: return '2';
case 3: return '3';
case 4: return '4';
case 5: return '5';
case 6: return '6';
case 7: return '7';
case 8: return '8';
case 9: return '9';
case 10: return 'A';
case 11: return 'B';
case 12: return 'C';
case 13: return 'D';
case 14: return 'E';
case 15: return 'F';
default:
System.out.println("Wrong key inputted!");
}
}
return n;
Note that I have made a lot of mistake. I have no idea where to go from here.
Java's Integer class has built-in functions to return the Strings, for hex toHexString, for binary toBinaryString and for octal toOctalString. Hope this helps..
UPDATE
Your logic is correct and working, however there were few errors in the code, have a look: