|
1 | 1 | package com.thealgorithms.conversions;
|
2 | 2 |
|
3 |
| -import java.util.Scanner; |
4 |
| - |
| 3 | +/** |
| 4 | + * Utility class for converting a hexadecimal string to its decimal representation. |
| 5 | + * <p> |
| 6 | + * A hexadecimal number uses the base-16 numeral system, with the following characters: |
| 7 | + * <ul> |
| 8 | + * <li>Digits: 0-9</li> |
| 9 | + * <li>Letters: A-F (case-insensitive)</li> |
| 10 | + * </ul> |
| 11 | + * Each character represents a power of 16. For example: |
| 12 | + * <pre> |
| 13 | + * Hexadecimal "A1" = 10*16^1 + 1*16^0 = 161 (decimal) |
| 14 | + * </pre> |
| 15 | + * |
| 16 | + * <p>This class provides a method to perform the conversion without using built-in Java utilities.</p> |
| 17 | + */ |
5 | 18 | public final class HexaDecimalToDecimal {
|
6 | 19 | private HexaDecimalToDecimal() {
|
7 | 20 | }
|
8 | 21 |
|
9 |
| - // convert hexadecimal to decimal |
| 22 | + /** |
| 23 | + * Converts a hexadecimal string to its decimal integer equivalent. |
| 24 | + * <p>The input string is case-insensitive, and must contain valid hexadecimal characters [0-9, A-F].</p> |
| 25 | + * |
| 26 | + * @param hex the hexadecimal string to convert |
| 27 | + * @return the decimal integer representation of the input hexadecimal string |
| 28 | + * @throws IllegalArgumentException if the input string contains invalid characters |
| 29 | + */ |
10 | 30 | public static int getHexaToDec(String hex) {
|
11 | 31 | String digits = "0123456789ABCDEF";
|
12 | 32 | hex = hex.toUpperCase();
|
13 | 33 | int val = 0;
|
| 34 | + |
14 | 35 | for (int i = 0; i < hex.length(); i++) {
|
15 | 36 | int d = digits.indexOf(hex.charAt(i));
|
| 37 | + if (d == -1) { |
| 38 | + throw new IllegalArgumentException("Invalid hexadecimal character: " + hex.charAt(i)); |
| 39 | + } |
16 | 40 | val = 16 * val + d;
|
17 | 41 | }
|
18 |
| - return val; |
19 |
| - } |
20 | 42 |
|
21 |
| - // Main method gets the hexadecimal input from user and converts it into Decimal output. |
22 |
| - public static void main(String[] args) { |
23 |
| - String hexaInput; |
24 |
| - int decOutput; |
25 |
| - Scanner scan = new Scanner(System.in); |
26 |
| - |
27 |
| - System.out.print("Enter Hexadecimal Number : "); |
28 |
| - hexaInput = scan.nextLine(); |
29 |
| - |
30 |
| - // convert hexadecimal to decimal |
31 |
| - decOutput = getHexaToDec(hexaInput); |
32 |
| - /* |
33 |
| - Pass the string to the getHexaToDec function |
34 |
| - and it returns the decimal form in the variable decOutput. |
35 |
| - */ |
36 |
| - System.out.println("Number in Decimal: " + decOutput); |
37 |
| - scan.close(); |
| 43 | + return val; |
38 | 44 | }
|
39 | 45 | }
|
0 commit comments