- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathHexaDecimalToDecimal.java
45 lines (41 loc) · 1.5 KB
/
HexaDecimalToDecimal.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
packagecom.thealgorithms.conversions;
/**
* Utility class for converting a hexadecimal string to its decimal representation.
* <p>
* A hexadecimal number uses the base-16 numeral system, with the following characters:
* <ul>
* <li>Digits: 0-9</li>
* <li>Letters: A-F (case-insensitive)</li>
* </ul>
* Each character represents a power of 16. For example:
* <pre>
* Hexadecimal "A1" = 10*16^1 + 1*16^0 = 161 (decimal)
* </pre>
*
* <p>This class provides a method to perform the conversion without using built-in Java utilities.</p>
*/
publicfinalclassHexaDecimalToDecimal {
privateHexaDecimalToDecimal() {
}
/**
* Converts a hexadecimal string to its decimal integer equivalent.
* <p>The input string is case-insensitive, and must contain valid hexadecimal characters [0-9, A-F].</p>
*
* @param hex the hexadecimal string to convert
* @return the decimal integer representation of the input hexadecimal string
* @throws IllegalArgumentException if the input string contains invalid characters
*/
publicstaticintgetHexaToDec(Stringhex) {
Stringdigits = "0123456789ABCDEF";
hex = hex.toUpperCase();
intval = 0;
for (inti = 0; i < hex.length(); i++) {
intd = digits.indexOf(hex.charAt(i));
if (d == -1) {
thrownewIllegalArgumentException("Invalid hexadecimal character: " + hex.charAt(i));
}
val = 16 * val + d;
}
returnval;
}
}