-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathOctalToHexadecimal.java
61 lines (53 loc) · 1.94 KB
/
OctalToHexadecimal.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.thealgorithms.conversions;
/**
* Class for converting an Octal number to its Hexadecimal equivalent.
*
* @author Tanmay Joshi
*/
public final class OctalToHexadecimal {
private static final int OCTAL_BASE = 8;
private static final int HEX_BASE = 16;
private static final String HEX_DIGITS = "0123456789ABCDEF";
private OctalToHexadecimal() {
}
/**
* Converts an Octal number (as a string) to its Decimal equivalent.
*
* @param octalNumber The Octal number as a string
* @return The Decimal equivalent of the Octal number
* @throws IllegalArgumentException if the input contains invalid octal digits
*/
public static int octalToDecimal(String octalNumber) {
if (octalNumber == null || octalNumber.isEmpty()) {
throw new IllegalArgumentException("Input cannot be null or empty");
}
int decimalValue = 0;
for (int i = 0; i < octalNumber.length(); i++) {
char currentChar = octalNumber.charAt(i);
if (currentChar < '0' || currentChar > '7') {
throw new IllegalArgumentException("Incorrect octal digit: " + currentChar);
}
int currentDigit = currentChar - '0';
decimalValue = decimalValue * OCTAL_BASE + currentDigit;
}
return decimalValue;
}
/**
* Converts a Decimal number to its Hexadecimal equivalent.
*
* @param decimalNumber The Decimal number
* @return The Hexadecimal equivalent of the Decimal number
*/
public static String decimalToHexadecimal(int decimalNumber) {
if (decimalNumber == 0) {
return "0";
}
StringBuilder hexValue = new StringBuilder();
while (decimalNumber > 0) {
int digit = decimalNumber % HEX_BASE;
hexValue.insert(0, HEX_DIGITS.charAt(digit));
decimalNumber /= HEX_BASE;
}
return hexValue.toString();
}
}