Tag Archives: swing

Java Base Converter

Java Converter is a simple application I made to convert values in various bases (decimal, hexadecimal, octal, binary).
I know Java’s framework already provides methods to do such operations but I wanted to implement the algorithms.

Here is a snippet for the octal to decimal conversion:

@Override
public long toDecimal(String value)
throws NumberFormatException
{
	/* Stop execution if the value is empty or invalid. */
	if(value.isEmpty())
		throw new NumberFormatException("Empty string is not an octal number.");
	if(!checkBase(value))
		throw new NumberFormatException("The sequence is not an octal number.");
 
	/* Init variables. */
	long ret = 0;
	int length = value.length();
	int temp;
 
	/* Generate decimal value. */
	for(int i=0 ; i<length ; ++i)
	{
		temp = (int) value.charAt(length-(i+1)) - 48;
		if((temp < 0) || (temp > 7))
		{
			throw new NumberFormatException("The sequence is not an octal number.");
		}
		else
		{
			ret += temp*Math.round(Math.pow(2, 3*i));
		}
	}
 
	return ret;
}

This little API uses a strategy pattern so you can add any other bases and implements the methods in the current classes.
To make it easier I have created a GUI application in Swing which use this API.