Skip to content

Commit 25b6aeb

Browse files
authored
refactor: DecimalToHexadecimal (#5337)
1 parent d80fd0c commit 25b6aeb

File tree

4 files changed

+56
-65
lines changed

4 files changed

+56
-65
lines changed

src/main/java/com/thealgorithms/conversions/DecimalToHexaDecimal.java

-51
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.thealgorithms.conversions;
2+
3+
/**
4+
* This class provides a method to convert a decimal number to a hexadecimal string.
5+
*/
6+
final class DecimalToHexadecimal {
7+
private static final int SIZE_OF_INT_IN_HALF_BYTES = 8;
8+
private static final int NUMBER_OF_BITS_IN_HALF_BYTE = 4;
9+
private static final int HALF_BYTE_MASK = 0x0F;
10+
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
11+
12+
private DecimalToHexadecimal() {
13+
}
14+
15+
/**
16+
* Converts a decimal number to a hexadecimal string.
17+
* @param decimal the decimal number to convert
18+
* @return the hexadecimal representation of the decimal number
19+
*/
20+
public static String decToHex(int decimal) {
21+
StringBuilder hexBuilder = new StringBuilder(SIZE_OF_INT_IN_HALF_BYTES);
22+
for (int i = SIZE_OF_INT_IN_HALF_BYTES - 1; i >= 0; --i) {
23+
int currentHalfByte = decimal & HALF_BYTE_MASK;
24+
hexBuilder.insert(0, HEX_DIGITS[currentHalfByte]);
25+
decimal >>= NUMBER_OF_BITS_IN_HALF_BYTE;
26+
}
27+
return removeLeadingZeros(hexBuilder.toString().toLowerCase());
28+
}
29+
30+
private static String removeLeadingZeros(String str) {
31+
if (str == null || str.isEmpty()) {
32+
return str;
33+
}
34+
35+
int i = 0;
36+
while (i < str.length() && str.charAt(i) == '0') {
37+
i++;
38+
}
39+
40+
return i == str.length() ? "0" : str.substring(i);
41+
}
42+
}

src/test/java/com/thealgorithms/conversions/DecimalToHexaDecimalTest.java

-14
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.thealgorithms.conversions;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.params.ParameterizedTest;
6+
import org.junit.jupiter.params.provider.CsvSource;
7+
8+
public class DecimalToHexadecimalTest {
9+
@ParameterizedTest
10+
@CsvSource({"0, 0", "1, 1", "10, a", "15, f", "16, 10", "255, ff", "190, be", "1800, 708"})
11+
void testDecToHex(int decimal, String expectedHex) {
12+
assertEquals(expectedHex, DecimalToHexadecimal.decToHex(decimal));
13+
}
14+
}

0 commit comments

Comments
 (0)