Skip to content

Commit 0fde3bf

Browse files
author
alxkm
committed
refactor: DecimalToHexadecimal
1 parent 7c58b19 commit 0fde3bf

File tree

4 files changed

+43
-65
lines changed

4 files changed

+43
-65
lines changed

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

Lines changed: 0 additions & 51 deletions
This file was deleted.
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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 hexBuilder.toString().toLowerCase();
28+
}
29+
}

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

Lines changed: 0 additions & 14 deletions
This file was deleted.
Lines changed: 14 additions & 0 deletions
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, 00000000", "1, 00000001", "10, 0000000a", "15, 0000000f", "16, 00000010", "255, 000000ff", "190, 000000be", "1800, 00000708"})
11+
void testDecToHex(int decimal, String expectedHex) {
12+
assertEquals(expectedHex, DecimalToHexadecimal.decToHex(decimal));
13+
}
14+
}

0 commit comments

Comments
 (0)