conversion decimal to hexadecimal

This commit is contained in:
Adan Rodriguez 2019-01-30 11:23:42 -03:00
parent 4f1fceeb7f
commit c7f8f772c0
2 changed files with 43 additions and 0 deletions

View File

@ -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;
}
}

View File

@ -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"));
}
}