Binary Addition
Add two binary numbers
/*
* Enter two numbers in base 10, convert them in binary
* and find their sum
*/
import java.io.*;
class BinarySum
{
public static void main(String args[])throws IOException
{
int m,n,u,v,x,y,z,p,r,i,d,e;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the first number (base 10): ");
m= Integer.parseInt(br.readLine());
System.out.print("Enter the second number (base 10): ");
n= Integer.parseInt(br.readLine());
//Arrays to store numbers in binary form
int a[]= new int [20];
int b[]=new int [20];
//Array to store the sum of binary numbers
int c[]= new int[50];
p=m;
x=0;
//Convert the number to binary and store in an array
while(p>0)
{
a[x++]=p%2;
p=p/2;
}
System.out.print(m+"=");
for(i=x-1;i>=0;i--)
{
System.out.print(a[i]);
}
System.out.println();
p=n;
y=0;
//Convert the number to binary and store in an array
while(p>0)
{
b[y++]=p%2;
p=p/2;
}
System.out.print(n+"=");
for(i=y-1;i>=0;i--)
{
System.out.print(b[i]);
}
e=z=u=v=0;
/*
* To understand the following logic, you need to know binary addition.
* In binary addition:
* 0 + 0 = 0
* 0 + 1 = 1
* 1 + 0 = 1
* 1 + 1 = 10 (read as 0 CARRY 1)
* 1 + 1 + 1 = 11 ( read as 1 CARRY 1)
*/
do{
d=a[u]+b[v]+e; //Add the digits
if(d==2){
c[z++]=0;
e=1;
}
else if(d==3){
c[z++]=1;
e=1;
}
else{
c[z++]=d;
e=0;
}
u++;
v++;
}while(u < x && v < y);
//If any digit is left in the first array copy them
// into the sum array after adding the carry
if(u < x){
while(u < x){
d=a[u++]+e;
if(d==2){
c[z++]=0;
e=1;
}
else if(d==3){
c[z++]=1;
e=1;
}
else{
c[z++]=d;
e=0;
}
}
}
//If any digit is left in the second array copy them
// into the sum array after adding the carry
else if(v < y){
while(v < y){
d=b[v++]+e;
if(d==2){
c[z++]=0;
e=1;
}
else if(d==3){
c[z++]=1;
e=1;
}
else{
c[z++]=d;
e=0;
}
}
}
//If a carry is still left copy it at the last in the sum array
if(e==1){
c[z++]=e;
}
System.out.print("\nSum of the two binary numbers : ");
for(i=z-1;i>=0;i--)
System.out.print(c[i]);
}//end of main
}//end of class
Have something to say? Log in to comment on this post.
0 comments