Thursday, May 21, 2009

Converting decimals into different base numbers

I have this function that might be useful and interesting for you. Probably some of us are thinking how to convert a decimal number into hexadecimal, octal and binary. To those readers that never heard of these four words, decimal is a base 10 number, hexadecimal is a base 16 number, octal is a base 8 number and binary is a base 2 number. I wrote this function simply because I wanted to learn what happens behind the API methods in the Java SDK that help you to convert a given decimal into the three different base numbers.

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);


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);
}
}
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 void main(String[] args) {
System.out.println(DecimalConverter.toOct(207));
System.out.println(DecimalConverter.toBin(207));
System.out.println(DecimalConverter.toHex(207));
}
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.

0 comments:

Post a Comment