Friday, 20 December 2019

Java Program for Binary, Decimal, Octal and HEX conversions

import java.util.*;
class Convert
{
public void binary(int n)
{
int s=0,pos=0;
while(n>0)
{
int dg=n%2;
s=s+dg*(int)Math.pow(10,pos++);
n=n/2;
}
System.out.println(s);
}
public void octal(int n)
{
int s=0,pos=0;
while(n>0)
{
int dg=n%8;
s=s+dg*(int)Math.pow(10,pos++);
n=n/8;
}
System.out.println(s);
}
public void hexadecimal(int n)
{
String s="";
int pos=0;
while(n>0)
{
int dg=n%16;
if(dg>9)
dg=dg+55;
else
dg=dg+48;
s=(char)dg+s;
n=n/16;
}
System.out.println(s);
}
public void binaryNO(int n)
{
int pos=0,s=0;
while(n>0)
{
int dg=n%10;
s=s+dg*(int)Math.pow(2,pos++);
n=n/10;
}
System.out.println(s);
}
public void octalNO(int n)
{
int pos=0,s=0;
while(n>0)
{
int dg=n%10;
s=s+dg*(int)Math.pow(8,pos++);
n=n/10;
}
System.out.println(s);
}
public void hexadecimalNO(String s)
{
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0,pos=0;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
int d = digits.indexOf(c);
val =16*val + d;
}
System.out.println( val);
}
}
public class Convertmain
{
public static void main(String args[])
{
Convert ob=new Convert();
Scanner sc=new Scanner(System.in);
System.out.println("Enter your choice : - \n1 for Decimal to Binary \n2 for Decimal to Octal \n3 for Decimal to Hexadecimal \n4 for Binary to Decimal \n5 for Octal to Decimal \n6 for Hexadecimal to Decimal");
int ch=sc.nextInt();
String s="";
int n=0;
System.out.println("\nEnter your value");
if(ch==6)
s=sc.next();
else
n=sc.nextInt();
System.out.println("\nYour result is");
switch(ch)
{
case 1:ob.binary(n);
break;
case 2:ob.octal(n);
break;
case 3:ob.hexadecimal(n);
break;
case 4:ob.binaryNO(n);
break;
case 5:ob.octalNO(n);
break;
case 6:ob.hexadecimalNO(s);
break;
default:System.out.println("Wrong input");
}
}
}

No comments:

Post a Comment

Convey your thoughts to authors.