import org.junit.*;
import static org.junit.Assert.*;
public class HexValue
{
private static final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
private static String toHexValue(int baseValue) throws IllegalArgumentException
{
StringBuilder builder = new StringBuilder();
if(baseValue < 0)
{
throw new IllegalArgumentException("Given base value "+baseValue+" is less than zero");
}
else if(baseValue == 0)
{
return String.valueOf(0);
}
while(baseValue > 0)
{
int mod = baseValue%16;
builder.insert(0,hexArray[mod]);
baseValue = baseValue/16;
}
return builder.toString();
}
@Test public void testZero()
{
assertEquals("0",HexValue.toHexValue(0));
}
@Test (expected=IllegalArgumentException.class)
public void testNegative()
{
HexValue.toHexValue(-8);
}
@Test
public void testValidInput()
{
assertEquals("A0",HexValue.toHexValue(160));
assertEquals("100",HexValue.toHexValue(256));
assertEquals("EA",HexValue.toHexValue(234));
}
public static void main(String a[])
{
if(a.length != 1)
{
System.out.println("Help: java HexValue [baseValue]");
return;
}
System.out.println("Hexa Decimal value of "+a[0]+" is "+HexValue.toHexValue(Integer.parseInt(a[0])));
}
}
No comments:
Post a Comment