conversion decimal to hexadecimal
This commit is contained in:
parent
4f1fceeb7f
commit
c7f8f772c0
26
src/main/java/com/conversions/DecimalToHexadecimal.java
Normal file
26
src/main/java/com/conversions/DecimalToHexadecimal.java
Normal 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;
|
||||
}
|
||||
}
|
17
src/test/java/com/conversions/DecimalToHexadecimalTest.java
Normal file
17
src/test/java/com/conversions/DecimalToHexadecimalTest.java
Normal 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"));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user