The methods that are available for us the developers in the Java 1.5 SDK are:
Integer.toBinaryString(input);
Integer.toOctalString(input);
Integer.toHexString(input);
From the method as shown, we have 16 characters in the array "code". This is because we want to accommodate all the valid the characters in base 16 numbers (hexadecimals). This method is quite a recursive method to convert the base 10 numbers (decimals) into 3 different bases of numbers. I hope you find these method useful. :) We can make use of this method by calling these static methods in the DecimalConverter class. Static methods are especially easy and useful when we want to call or make use of them from other classes. This is how the method is demonstrated.
public static class DecimalConverter{
static StringBuffer result = new StringBuffer();
static int divisorBIN = 2;
static int divisorOCT = 8;
static int divisorHEX = 16;
static char[] code = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
public static String converterHelper(int number, int divisor) {
if (number == 0) {
return "";
}
else {
converterHelper(number/divisor, divisor);
result.append(code[number%divisor]);
}
return result.toString();
}
public static String toHex(int number) {
//reset StringBuffer result
result.setLength(0);
return converterHelper(number, divisorHEX);
}
public static String toOct(int number) {
//reset StringBuffer result
result.setLength(0);
return converterHelper(number, divisorOCT);
}
public static String toBin(int number){
//reset StringBuffer result
result.setLength(0);
return converterHelper(number, divisorBIN);
}
}
The recursion takes place in this statement converterHelper(number/divisor, divisor);. converterHelper method calls itself as long as the number is not 0 and then it looks into the array and find the matching character according to the index from the modulo operation. You may try out this method and use the numbers in the conversion table to determine if this helper class is useful for you. Click here to view the conversion table.
public static void main(String[] args) {
System.out.println(DecimalConverter.toOct(207));
System.out.println(DecimalConverter.toBin(207));
System.out.println(DecimalConverter.toHex(207));
}
0 comments:
Post a Comment