Java Hexadecimal to Decimal Conversion
In Mathematics, we use various positional numbering schemes for representing numbers. We are familiar with decimal numbering system which uses a base of 10. Two other commonly used numbering systems in computing are hexadecimal (base 16) and binary (base 2).
When we represent a number in hexadecimal system, we use the symbols 0 to 9 and letters A, B, C, D, E and F. Decimal numbering system uses symbols 0 to 9. A value D in hexadecimal corresponds to the decimal value of 13. Following are some of the examples of hexadecimal to decimal conversion,
1AF = 1*16*16 + 10*16 + 15 = 256 + 160 + 15 = 431
224B = 2*16*16*16 + 2*16*16 + 4*16 + 11 = 8192 + 512 + 64 + 11 = 8779
The conversion involves the following steps,
- Find the decimal value of each digit in hexadecimal string
- Multiply each decimal value with 16 raised to the power of the position of the digit
- Add all the values to get the equivalent decimal value
The following program uses the above algorithm to convert hexadecimal string to its corresponding decimal value,
/** * This program converts a hexadecimal value to its corresponding decimal value * @author QPT */ public class HexToDecimal { public static String HEX_CHARACTERS="0123456789ABCDEF"; public static void main(String[] args) { HexToDecimal hd = new HexToDecimal(); String hexValue = "87BBDF"; int dec = hd.hex2dec(hexValue); System.out.println("Decimal value of "+hexValue+" is "+dec); } /** * * @param hexValue hex value for decimal conversion * @return decimal value */ private int hex2dec(String hexValue) { hexValue = hexValue.toUpperCase(); int decimalResult = 0; for(int i=0;i<hexValue.length();i++) { char digit = hexValue.charAt(i); int digitValue = HEX_CHARACTERS.indexOf(digit); decimalResult = decimalResult*16+digitValue; } return decimalResult; } }