Hexadecimal to Decimal Conversion in Java
Hexadecimal to Decimal Conversion
Hexadecimal to Decimal conversion is the process of converting a hexadecimal number (base-16) into its equivalent decimal number (base-10). Each hexadecimal digit represents a power of 16.
For example, the hexadecimal number 1F is equal to decimal 31 because:
(1 × 16¹) + (F × 16⁰) = 16 + 15 = 31
We will explore three methods to convert a hexadecimal number to a decimal number using Java programming.
Method 1: Using Loop
We extract each digit of the hexadecimal number, multiply it by the corresponding power of 16, and sum the results.
import java.util.Scanner; public class Main { public static int hexToDecimal(String hex) { int decimal = 0, base = 1; for (int i = hex.length() - 1; i >= 0; i--) { char digit = hex.charAt(i); int value = (digit >= '0' && digit <= '9') ? digit - '0' : digit - 'A' + 10; decimal += value * base; base *= 16; } return decimal; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a hexadecimal number: "); String hex = scanner.next().toUpperCase(); System.out.println("Decimal equivalent: " + hexToDecimal(hex)); scanner.close(); } }
Output:
Enter a hexadecimal number: 1F Decimal equivalent: 31
Method 2: Using Built-in Function
We can use Java's Integer.parseInt() method to directly convert a hexadecimal number to a decimal number.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a hexadecimal number: "); String hex = scanner.next().toUpperCase(); int decimal = Integer.parseInt(hex, 16); System.out.println("Decimal equivalent: " + decimal); scanner.close(); } }
Output:
Enter a hexadecimal number: 1F Decimal equivalent: 31
Method 3: Using Recursion
We recursively extract each digit and multiply it by the corresponding power of 16.
import java.util.Scanner; public class Main { public static int hexToDecimalRecursive(String hex, int length, int index) { if (index == length) return 0; char digit = hex.charAt(index); int value = (digit >= '0' && digit <= '9') ? digit - '0' : digit - 'A' + 10; return value * (int) Math.pow(16, length - index - 1) + hexToDecimalRecursive(hex, length, index + 1); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a hexadecimal number: "); String hex = scanner.next().toUpperCase(); System.out.println("Decimal equivalent: " + hexToDecimalRecursive(hex, hex.length(), 0)); scanner.close(); } }
Output:
Enter a hexadecimal number: 1F Decimal equivalent: 31