Tuesday, November 2, 2010

Number system convert from decimal to octal or binary or hexa decimal in java

import java.io.*;
public class convert_arr
{
public static void dec_bin(int n)
{
int f=0,p=0,j;
int a[]=new int[100];
while(n>0)
{
f=n%2;
a[p++]=f;
n=n/2;
}
for(j=p-1;j>=0;j--)
{
System.out.print(a[j]);
}
}

public static void dec_oct(int n)
{
int f=0,p=0,j;
int b[]=new int[100];
while(n>0)
{
f=n%8;
b[p++]=f;
n=n/8;
}
for(j=p-1;j>=0;j--)
{
System.out.print(b[j]);
}
}

public static void dec_hex(int n)
{
int p=0,f=0,j;
int c[]=new int[100];
while(n>0)
{
f=n%16;
c[p++]=f;
n=n/16;
}
for(j=p-1;j>=0;j--)
{
if(c[j]>9)
System.out.print((char)(c[j]+55));
else
System.out.print(c[j]);
}
}
public static void main()throws IOException
{
int n;
convert_arr obj=new convert_arr();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.print("Enter decimal number - ");
n=Integer.parseInt(br.readLine());
System.out.println("1.binary\n2.octal\n3.hexadec\n");
System.out.print("Enter your choice-");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
obj.dec_bin(n);
break;
case 2:
obj.dec_oct(n);
break;
case 3:
obj.dec_hex(n);
break;
}
}
}












No comments: