Skip to content

refactor: DecimalToHexadecimal #5337

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.thealgorithms.conversions;

/**
* This class provides a method to convert a decimal number to a hexadecimal string.
*/
final class DecimalToHexadecimal {
private static final int SIZE_OF_INT_IN_HALF_BYTES = 8;
private static final int NUMBER_OF_BITS_IN_HALF_BYTE = 4;
private static final int HALF_BYTE_MASK = 0x0F;
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

private DecimalToHexadecimal() {
}

/**
* Converts a decimal number to a hexadecimal string.
* @param decimal the decimal number to convert
* @return the hexadecimal representation of the decimal number
*/
public static String decToHex(int decimal) {
StringBuilder hexBuilder = new StringBuilder(SIZE_OF_INT_IN_HALF_BYTES);
for (int i = SIZE_OF_INT_IN_HALF_BYTES - 1; i >= 0; --i) {
int currentHalfByte = decimal & HALF_BYTE_MASK;
hexBuilder.insert(0, HEX_DIGITS[currentHalfByte]);
decimal >>= NUMBER_OF_BITS_IN_HALF_BYTE;
}
return hexBuilder.toString().toLowerCase();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.thealgorithms.conversions;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

public class DecimalToHexadecimalTest {
@ParameterizedTest
@CsvSource({"0, 00000000", "1, 00000001", "10, 0000000a", "15, 0000000f", "16, 00000010", "255, 000000ff", "190, 000000be", "1800, 00000708"})
void testDecToHex(int decimal, String expectedHex) {
assertEquals(expectedHex, DecimalToHexadecimal.decToHex(decimal));
}
}