- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathDecimalToHexadecimal.java
42 lines (36 loc) · 1.45 KB
/
DecimalToHexadecimal.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
packagecom.thealgorithms.conversions;
/**
* This class provides a method to convert a decimal number to a hexadecimal string.
*/
finalclassDecimalToHexadecimal {
privatestaticfinalintSIZE_OF_INT_IN_HALF_BYTES = 8;
privatestaticfinalintNUMBER_OF_BITS_IN_HALF_BYTE = 4;
privatestaticfinalintHALF_BYTE_MASK = 0x0F;
privatestaticfinalchar[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
privateDecimalToHexadecimal() {
}
/**
* Converts a decimal number to a hexadecimal string.
* @param decimal the decimal number to convert
* @return the hexadecimal representation of the decimal number
*/
publicstaticStringdecToHex(intdecimal) {
StringBuilderhexBuilder = newStringBuilder(SIZE_OF_INT_IN_HALF_BYTES);
for (inti = SIZE_OF_INT_IN_HALF_BYTES - 1; i >= 0; --i) {
intcurrentHalfByte = decimal & HALF_BYTE_MASK;
hexBuilder.insert(0, HEX_DIGITS[currentHalfByte]);
decimal >>= NUMBER_OF_BITS_IN_HALF_BYTE;
}
returnremoveLeadingZeros(hexBuilder.toString().toLowerCase());
}
privatestaticStringremoveLeadingZeros(Stringstr) {
if (str == null || str.isEmpty()) {
returnstr;
}
inti = 0;
while (i < str.length() && str.charAt(i) == '0') {
i++;
}
returni == str.length() ? "0" : str.substring(i);
}
}