Write a program in java to convert Hexdecimal to binary
import java.util.Scanner;
class hexadecimal_to_binary
{
public static void main(String[]args)
{
Scanner ob=new Scanner(System.in);
System.out.println("enter hexadecimal number");
String s=ob.nextLine();
int x=s.length();
char ch=' ';
for (int i=0;i<x;i++)
{
ch=s.charAt(i);
if ((ch>=48 && ch<=57) || ch=='A' || ch=='B' || ch=='C' || ch=='D' || ch=='E' || ch=='F')
{}
else
{
System.out.println("invalid input");
System.exit(0);
}
}
int d=0;
int m=0;
String s1="",ns="",fin="";
for (int i=x-1;i>=0;i--)
{
ch=s.charAt(i);
if (ch=='A')
{
m=10;
}
else if (ch=='B')
{
m=11;
}
else if (ch=='C')
{
m=12;
}
else if (ch=='D')
{
m=13;
}
else if (ch=='E')
{
m=14;
}
else if (ch=='F')
{
m=15;
}
else
{
s1=Character.toString(ch);
m=Integer.parseInt(s1);
}
while(m>0)
{
d=m%2;
ns=Integer.toString(d)+ns;
m=m/2;
}
if (ns.length()==1)
{
ns="000"+ns;
}
else if(ns.length()==2)
{
ns="00"+ns;
}
else if(ns.length()==3)
{
ns="0"+ns;
}
fin=ns+fin;
ns="";
}
char chz=' ';
for (int l=0;l<x;l++)
{
chz=s.charAt(l);
if (chz=='0')
{
fin=fin.substring(0,4*l)+"0000"+fin.substring(4*l);
}
}
System.out.println("The binary number is "+fin);
}
}
class hexadecimal_to_binary
{
public static void main(String[]args)
{
Scanner ob=new Scanner(System.in);
System.out.println("enter hexadecimal number");
String s=ob.nextLine();
int x=s.length();
char ch=' ';
for (int i=0;i<x;i++)
{
ch=s.charAt(i);
if ((ch>=48 && ch<=57) || ch=='A' || ch=='B' || ch=='C' || ch=='D' || ch=='E' || ch=='F')
{}
else
{
System.out.println("invalid input");
System.exit(0);
}
}
int d=0;
int m=0;
String s1="",ns="",fin="";
for (int i=x-1;i>=0;i--)
{
ch=s.charAt(i);
if (ch=='A')
{
m=10;
}
else if (ch=='B')
{
m=11;
}
else if (ch=='C')
{
m=12;
}
else if (ch=='D')
{
m=13;
}
else if (ch=='E')
{
m=14;
}
else if (ch=='F')
{
m=15;
}
else
{
s1=Character.toString(ch);
m=Integer.parseInt(s1);
}
while(m>0)
{
d=m%2;
ns=Integer.toString(d)+ns;
m=m/2;
}
if (ns.length()==1)
{
ns="000"+ns;
}
else if(ns.length()==2)
{
ns="00"+ns;
}
else if(ns.length()==3)
{
ns="0"+ns;
}
fin=ns+fin;
ns="";
}
char chz=' ';
for (int l=0;l<x;l++)
{
chz=s.charAt(l);
if (chz=='0')
{
fin=fin.substring(0,4*l)+"0000"+fin.substring(4*l);
}
}
System.out.println("The binary number is "+fin);
}
}
Post a Comment