Thursday, November 18, 2010

Program for any base to any base in java

import java.io.*;
class anybase_anybase
{
public String deci_to_other(int no,int b)
{
String cno="";
int r;
         while(no>0)
         {
             r=no%b;
             if(r>9)
             {
                 r+=55;
                 char c=(char)r;
                 cno=c+cno;
                }
                else
                {
                    cno=r+cno;
                }
                no=no/b;
            }
                   return cno;
           
        }
   
   
    public int other_to_decimal (String s,int base)
{
int g,num=0,a=0;
   
  
int l=s.length();

for(int i=l-1;i>=0;i--)
{
char c=s.charAt(i);

if(c>=65 && c<=70)
{c-=55;

 g=c;

num=num+(g*((int)Math.pow(base,a)));
    }
    else
    {
        c-=48;
         g=c;
        
         num=num+(g*((int)Math.pow(base,a)));
        }
        a++;
    }
   return num;
}
   
   
    public  void meth()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        {
            System.out.println("enter choice");
            System.out.println("1.to convert from decimal number to number in other base");
            System.out.println("2.to convert from number in other base to decimal no");
            System.out.println("3.to convert no in any base to number in any base");
           
            int n=Integer.parseInt(br.readLine());
           
            switch(n)
            {
                case 1:
                {
                    System.out.println("enter no and base both ");
                    int no=Integer.parseInt(br.readLine());
                    int b=Integer.parseInt(br.readLine());
                   
                    String f=deci_to_other(no,b);
                    System.out.println(f);break;
               
            }
                case 2:
             {  
                    System.out.println("enter no in String and base");
                    String s=br.readLine();
                    int b=Integer.parseInt(br.readLine());
                   
                    int f=other_to_decimal(s,b);
                    System.out.println(f);break;
                } 
                    case 3:
                {
                    System.out.println("enter no ,its base and the base to which it is to be converted");
                     String s=br.readLine();
                 int b=Integer.parseInt(br.readLine());
                  int bas=Integer.parseInt(br.readLine());
                    int k=other_to_decimal(s,b);
                    String f=deci_to_other(k,bas);
                    System.out.println(f);
                }}
            }
                   
                }
            }
                   

No comments: