Eureka
Eureka

Reputation: 93

How to convert any number to any base?

 System.out.println("BASE CONVERTER");

 Scanner indigit = new Scanner( System.in );
 System.out.print("DIGIT REPRESENTATION: ");
 String digit =indigit.next();

 Scanner inbase1 = new Scanner( System.in );
 System.out.print("SOURCE BASE: ");
 int base1 =inbase1.nextInt();
 int decimal = Integer.parseInt(digit,base1);
 System.out.println("DECIMAL: " + decimal);

 Scanner inbase2 = new Scanner( System.in );
 System.out.print("TARGET BASE: ");
 int base2 =inbase2.nextInt();

 System.out.println("NEW NUMBER: " + Integer.toString(decimal, base2));

The code is working however I would like to add an option which determines whether the input is valid or not. For example "A" would be invalid under Base 2. Here is my attempt, but it doesn't work.

 int i;
 int len=digit.length();
 for (i = len - 1; i >= 0; i--)
{
    String value = Character.toString(a.charAt(i));
    if ((Integer.valueOf(((a.charAt(i))+""),16)) >= 16) System.out.print("Invalid Number");   

Upvotes: 1

Views: 1507

Answers (2)

WJS
WJS

Reputation: 40047

I think the easiest and most flexible way is to use BigInteger. It allows arbitrary sizes of integers, passed in as a string.

   public static void main(String[] args) {
        System.out.println(toBase("FF", 16, 10));
        System.out.println(toBase("FF", 16, 2));
        System.out.println(toBase("123", 2, 16));
        System.out.println(toBase("111111111111111111111111111111111111111111111111111",2, 16));
    }

This method does the following:

  • accepts a source and destination base.
  • returns the required conversion.
  • throws an exception if the base is inappropriate for the supplied number.
  • in the latter case, a null is returned.
    public static String toBase(String num, int srcBase, int dstBase) {
        try {
        BigInteger b = new BigInteger(num,srcBase);
        return b.toString(dstBase);
        } catch (Exception e) {
            System.out.println("Invalid argument : " + e.getLocalizedMessage());
        }
        return null;
    }       

The output of the above examples is:

255
11111111
7ffffffffffff
Invalid argument : For input string: "123" under radix 2
null

Upvotes: 2

andrewJames
andrewJames

Reputation: 22042

You are already most of the way there with your existing code. If you only want to know if the input is valid, you can catch the relevant exception:

try {
    int i = Integer.parseInt("A", 2);
} catch (NumberFormatException nfe) {
    // or however you want to handle the exception:
    System.out.println("Number format exception: " + nfe.getMessage());
}

Look at the definition here in the Javadoc.

Throws: NumberFormatException - if the String does not contain a parsable int

Upvotes: 3

Related Questions