Merge pull request #697 from arodriguez33/Development

Conversion
This commit is contained in:
Libin Yang 2019-01-31 21:09:19 +08:00 committed by GitHub
commit 023ddee5db
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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"));
}
}