The program to convert binary to decimal is as followsimport java.io.*;
class bcd
{
int k; // instance variable
bcd() // Default Constructor
{
k = 0;
}
public bcd(int n) // parameterised constructor
{
k=n;
}
private void disp()
{
int x[]=new int[32];
if(k%26gt;99999999 || k%26lt;0)
{
System.out.println("Number should be only of eight digit and it should be positive");
return;
}
int rem,r;
int y[]={0,0,0,0}; // array of size 4 taken to store a digit when converted into binary
int z=0;
System.out.print(k+" = ");
while(k%26gt;0)
{
rem=k%10; //Extracting the digits from decimal number
k=k/10;
for(int i=0;i%26lt;4;i++)
{
r=rem%2; // Convering the extracted digit into Binary
rem=rem/2;
y[i]=r;
}
for(int j=0;j%26lt;4;j++)
{
x[z]=y[j];
z++;
}
}
for(int j=31;j%26gt;=0;j--)
{
System.out.print(x[j]);
if(j%4==0)
System.out.print(" ");
} // closing of for loop
} // closing of disp method
public static void main()throws IOException
{
char c; // used to store 'y' or 'n' for continuing or terminating the program
do
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("*************** MENU ******************\n");
System.out.println("Enter 1 to display BCD equivalent of any eight digit Number\n ");
System.out.println("Enter 2 to perform BCD Addition of Two Numbers\n ");
System.out.println("Enter 3 to perform BCD Subtractionaddition of Two Numbers\n");
System.out.print(" Enter your choice : ");
int y=Integer.parseInt(br.readLine());
switch(y)
{
case 1: System.out.print("Enter The No. : ");
int lim=Integer.parseInt(br.readLine());
bcd B=new bcd(lim);
if(lim%26gt;99999999 || lim%26lt;0)
{
System.out.println("Number should be only of eight digit ");
}
else
{
System.out.println("\n\t\tBCD Equivalent\n");
B.disp();
}
break;
case 2: System.out.print("Enter First No. : ");
int n=Integer.parseInt(br.readLine());
System.out.print("Enter Second No. : ");
int m=Integer.parseInt(br.readLine());
int z = n+m;
bcd C=new bcd(z);
System.out.println(" \n\t\tBCD Addition : \n");
C.disp();
break;
case 3: System.out.print("Enter First No. : ");
int x=Integer.parseInt(br.readLine());
System.out.print("Enter Second No. : ");
int a=Integer.parseInt(br.readLine());
int w = x-a;
bcd D=new bcd(w);
System.out.println(" \n\t\tBCD Subtraction : \n");
D.disp();
break;
default : System.out.println("Invalid choice");
} // closing of switch case
System.out.print("\nDo you want to continue ? Press y/n :\t");
c=(char)br.read();
}while(c!='n'); // closing of do-while loop
} // closing of main function
} // closing of class|||Sorry, this program does not convert from binary to decimal. If you look at the main() program menu, you will see that it offers the choices of converting a decimal number into BCD or of doing BCD arithmetic. BCD is a coding system in which each decimal digit is individually coded into binary, thus
decimal 16
binary 0001 0000
BCD 0001 0110
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment