Using Java, we can covnert Binary, Octal, Hexadecimal numbers into Decimal number system easily. Java have seperate methods to convert Decimal numbers in to Binar, Octal and Hexadecimal. But, no seperate method to convert Binary, Octal, Hex into Decimal. Following code is designed using JDK1.5 which can convert any number into a Decimal equivatent.
This code run on DOS mode. You have to insert number you want to convert first. Then, base of the number you entered. Then program convert number in to Base 10 (Decimal) number System. The code comlete with error checking mechanisms.
Logic of the Program: (Pseudocode)
Use Variables:
chrArray[],status OF TYPE Character,
usersValue, usersBase, exponent, tempValue, count, result OF TYPE Integer
Begin
status = 'y'
Do
usersValue = 0000
usersBase = 2
tempValue = 0
exponent = 0
result = 0
Print "Enter Value to Convert: "
Read usersValue
Print "Enter Base of the Value: "
Read usersBase
for(count = 0 to usersValues.number_of_characters)
chrArray[count] = usersValues[character_at_count_index]
End
for((count = chrArray.no_of_items - 1) to -1)
if(chrArray[count] <= 9 && chrArray[count] >= 0) then
tempValue = chrArray[count]
else
if(usersBase != 16) then
Print "Error in value ", usersValue
else
switch (chrArray[count] = 'A')
case 'A': tempValue = 10
case 'B': tempValue = 11
case 'C': tempValue = 12
case 'D': tempValue = 13
case 'E': tempValue = 14
case 'F': tempValue = 15
default: Print "Error in value ", usersValue
End
End If
End If
result = result + tempValue * usersBase^exponent
exponent = exponent + 1
End
Print "Decimal value is ", result
Print "Press Y to repeat: "
Read status
while(status = 'y')
End
Java Source Code: (Save this as: ConvertNumberToDecimal.java and complie)
The output is shown at the bottom of the page.
import java.lang.Math;
import java.util.Scanner;
public class ConvertNumberToDecimal{
public static void main(String[] args) throws Exception{
//Program prints program title at first run.
System.out.println("\nConvert To Decimal Program \n");
//'status' is a Character variable used to repeat program if user wanted to
char status;
do{
/**Declaring variables and objects. Scanner object is used to read Keyboard input.
*'strNumber' to store number user want to convert. *To store base of the number strBase is used. Equivalent Integer type define to *manipulate data. Character array 'chrNumber' will hod the splitted number. 'exp' is to *control exponent and value is for hold final result.*/
Scanner scan = new Scanner(System.in);
String strNumber;
String strBase;
char[] chrNumber;
int intNumber=0000;
int intBase = 2;
int exp = 0;
int value = 0;
/**Getting user's Number to convert. To avoid ambiguous input, String.trim() has been used. *Entered value splits by String.toCharArray() method. */
System.out.print("\nInput Number: ");
strNumber = scan.next();
strNumber = strNumber.trim();
chrNumber = strNumber.toCharArray();
/**Getting user's Base of given number. To avoid ambiguous input, String.trim() has been used. *Entered value convert into Integer by Integer.parseInt() method. *This is same as intBase = Integer.parseInt((scan.next()).trim()); */
System.out.print("Input Base: ");
strBase = scan.next();
strBase = strBase.trim();
try{
intBase = Integer.parseInt(strBase);
}catch(Exception e){
System.out.println("\nNOTE:Value you entered as Base is incorrect. Please check again! \nDefault base (0) assigned insted");
}
/**Moving through the entered number. Loop starts checking last Character of the number and check whether it's a digit or not. *If it was a digit, then value will assigned to tempString and break the loop. Otherwise, (if a non-digit Character found) it checks *if base is 16. If base isn't 16, then the user input is incorrect. Error message will print. Otherwise non-digit Character check for *A,B,C,D,E and F and convert to corresponding value and break the loop. If character is not valied, error message will print.*/
for(int firstForLoop = chrNumber.length-1; firstForLoop>-1; firstForLoop--)
{
String tempString = “0”;
if((Character.isDigit(chrNumber[firstForLoop])))
{
if((chrNumber[firstForLoop]) < Integer.toString(intBase).charAt(0))
{
tempString = String.valueOf(chrNumber[firstForLoop]);
}
else
{
if(intBase != 16){
System.out.println("\nNOTE:Value you entered is incorrect. Please chack again! \nValue is larger than its base value.Defalt value (0) assigned insted.");}
else{
tempString = String.valueOf(chrNumber[firstForLoop]);}
}
}
else
{
if(intBase != 16)
{
System.out.println("\nNOTE:Value you entered is incorrect. Please chack again! \nDefalt value (0) assigned insted.");
tempString = "0";
}
else{
chrNumber[firstForLoop] = Character.toUpperCase(chrNumber[firstForLoop]);
switch (chrNumber[firstForLoop])
{
case 'A':
tempString = "10";
break;
case 'B':
tempString = "11";
break;
case 'C':
tempString = "12";
break;
case 'D':
tempString = "13";
break;
case 'E':
tempString = "14";
break;
case 'F':
tempString = "15";
break;
default:
System.out.println("\nNOTE:Value you entered is incorrect. Please chack again! \nA Defalt value (0000) assigned insted.");
tempString = "10";
}//end of switch
}//end of if
}//end of it
/**After proper value taken into tempString, required conversion is carry out. Number will multiplied by*corresponding power of base and prints value..*/
value += (Integer.parseInt(tempString)) * (Math.pow(intBase, exp));
System.out.println(chrNumber[firstForLoop] + " x " + intBase + "^" + exp + " = " + ((Integer.parseInt(tempString)) * Math.pow(intBase, exp)));
exp += 1;
}//end of for loop
System.out.println("Decimal of " + intNumber + " = " + value);
/**User can restart the program if pressed 'y'/'Y'. Any other input will stop the program and exits to the system*/
System.out.print("\nDo you want to run again (y/n)? ");
status = Character.toLowerCase((char)System.in.read());
}while(status == 'y');
}//end of main method
}//end of class
Program Designed and Uploaded by H.W Thushara Indika, Jayamine, Dambathugoda, Kithal Ella Road, Heeloya, Bandarawela, Sri Lanka (28th September 2009). Copy and modify as you wish and its your own risk.