Friday, January 29, 2016

Program in java to convert a number between any base

One of my friend was looking for a Java program which can convert the given number of any base to any desired base number. So I thought to write a simple program for this.

First create a class "conversion"
public class conversion{
}
Create the main method and get the user inputs using scanner.

public class conversion{

public static void main(String[] args) { System.out.println("Enter the number"); Scanner marut= new Scanner(System.in); String number=marut.nextLine(); System.out.println("Enter the Base of the number"); int fromBase = marut.nextInt(); System.out.println("Enter the Base to convert"); int toBase = marut.nextInt();

} }
In above main method, we get the number with the base which we want to convert.
Number is read in 
String number=marut.nextLine();

And we get the base of this number using 
int fromBase = marut.nextInt();

As this will be a whole number, we consider it as integer.

Similarly we get the base to which this number has to be converted to using
int toBase = marut.nextInt();

Now create another method called as "convertFromBaseToBase" which actually converts the number.

public static String convertFromBaseToBase(String str, int fromBase, int toBase){ //Convert from one base to other return Integer.toString(Integer.parseInt(str, fromBase), toBase); } 
This method the number to be converted from base and to base as the arguments and returns the converted value in string.
Below is the code which does the trick:

Integer.toString(Integer.parseInt(str, fromBase), toBase)


Now in the main method we call this method to get the converted value and then print the result

String result=convertFromBaseToBase(number,fromBase,toBase);
System.out.println("Converted value is: "+result);
the whole program looks like this:

package com.chapter2; import java.util.Scanner; public class conversion { /** * @param args */ public static void main(String[] args) { System.out.println("Enter the number"); Scanner marut= new Scanner(System.in); String number=marut.nextLine(); System.out.println("Enter the Base of the number"); int fromBase = marut.nextInt(); System.out.println("Enter the Base to convert"); int toBase = marut.nextInt(); String result=convertFromBaseToBase(number,fromBase,toBase); System.out.println("Converted value is: "+result); } public static String convertFromBaseToBase(String str, int fromBase, int toBase){ //convert from one base to another return Integer.toString(Integer.parseInt(str, fromBase), toBase); } }
You can run this program and the result is as shown below:


That's it. You can download this program here


No comments: