From c7f8f772c056f8c5a84d1fd448b5fdde1b5be1c8 Mon Sep 17 00:00:00 2001 From: Adan Rodriguez Date: Wed, 30 Jan 2019 11:23:42 -0300 Subject: [PATCH] conversion decimal to hexadecimal --- .../com/conversions/DecimalToHexadecimal.java | 26 +++++++++++++++++++ .../conversions/DecimalToHexadecimalTest.java | 17 ++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/main/java/com/conversions/DecimalToHexadecimal.java create mode 100644 src/test/java/com/conversions/DecimalToHexadecimalTest.java diff --git a/src/main/java/com/conversions/DecimalToHexadecimal.java b/src/main/java/com/conversions/DecimalToHexadecimal.java new file mode 100644 index 00000000..e41b825d --- /dev/null +++ b/src/main/java/com/conversions/DecimalToHexadecimal.java @@ -0,0 +1,26 @@ +package src.main.java.com.conversions; + +import java.math.BigInteger; + +public class DecimalToHexadecimal { + private static final char hexChars[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; + private static final BigInteger valueHex = new BigInteger("16"); + + /** + * This method converts and decimal number to a Hexadecimal number + * @param decimalStr + * @return hexadecimal number + */ + public String decimalToHex(String decimalStr){ + BigInteger decimal = new BigInteger(decimalStr); + + int rem; + String hex = ""; + while(decimal.compareTo(BigInteger.ZERO) > 0) { + rem = decimal.mod(valueHex).intValueExact(); + hex = hexChars[rem] + hex; + decimal = decimal.divide(valueHex); + } + return hex; + } +} diff --git a/src/test/java/com/conversions/DecimalToHexadecimalTest.java b/src/test/java/com/conversions/DecimalToHexadecimalTest.java new file mode 100644 index 00000000..6a9540eb --- /dev/null +++ b/src/test/java/com/conversions/DecimalToHexadecimalTest.java @@ -0,0 +1,17 @@ +package src.test.java.com.conversions; + +import org.junit.Assert; +import org.junit.Test; + +public class DecimalToHexadecimalTest { + + @Test + public void testDecimalToHexadecimalTest() { + DecimalToHexadecimal decimalToHexadecimal = new DecimalToHexadecimal(); + Assert.assertEquals("Incorrect Conversion", "F", decimalToHexadecimal.decimalToHex("15")); + Assert.assertEquals("Incorrect Conversion", "121", decimalToHexadecimal.decimalToHex("289")); + Assert.assertEquals("Incorrect Conversion", "AAAAAAAAAAAAAAAAAA1", decimalToHexadecimal.decimalToHex("50371909150609548946081")); + Assert.assertEquals("Incorrect Conversion", "A", decimalToHexadecimal.decimalToHex("10")); + Assert.assertEquals("Incorrect Conversion", "8B2F", decimalToHexadecimal.decimalToHex("35631")); + } +} \ No newline at end of file