Base Conversions

Java Snippet

Convert a number from one base to another base

This routine will convert a string representation of a number from one base to another base e.g. 71 (base 10 ) converts to 107 (base 8). This example uses arguments to obtain the initial information, and outputs to the System.out.

Try it here, although this is written in vbscript, the routine is the same. Note: the max. value is a vb long, 2.14 billion

eg 987654321              base 10 to base 16 converts to    3ADE68B1

Click to see versions in    vb     vbscript

 

There is little error handling - the conversions should be wrapped in try/catch blocks.

Java code

class BaseConversions
{
  public static void main(String args[])
  {
    String converted = convert(args[0],Double.parseDouble(args[1]),
    Double.parseDouble(args[2]));
    System.out.println(args[0] + " (base "+args[1]+")"+
      " converts to "+converted+ " (base "+args[2]+")");
    System.exit(0);
  }

  private static String convert(String oldNum,double base1,double base2)
  {
    long temp=0;
    int x = 0;
    String nextChar;
    String convertedNumber = "";
    String chars = "0123456789ABCDEFGHIJ";

    for(int i = 0; i < oldNum.length(); i++)
    {
      if(chars.indexOf(oldNum.substring(i,i+1)) > = base1 ||
             chars.indexOf(oldNum.substring(i,i+1)) < 0)
      {
         return "error - invalid data";
      }
    }

    for(int i = oldNum.length(); i > 0; i--)
   {
      nextChar = oldNum.substring(x,x+1);
      temp += chars.indexOf(nextChar)*Math.pow(base1,i-1);
      x++;
    }

    x=0;
    while(temp > Math.pow(base2,x))
    {
      x++;
    }
    int index = 0;
    for(int i=1; i<=x; i++)
    {
    index = (int)(temp/Math.pow(base2,x-i));
    convertedNumber += chars.substring(index,index+1);
    temp-= index*Math.pow(base2,x-i);
    }

    return convertedNumber;
  }
}

 


back     top   main page    vb snippets page      java snippets page     vbscript snippets page   email    Page last modified