The BOTTOM LINE Quote Of The Day

The BOTTOM LINE Quote Of The Day

Don't Ever Tell GOD How BIG Your Problems are.
Just Tell Your Problems How BIG your GOD is ;)

Sunday, October 9, 2011

Adding of Two Numbers in Binary Form


#include<stdio.h>
#include<conio.h>
#include<math.h>

 void main()
  {
    clrscr();
     int i,num1,num2,num3=0,nd1=0,nd2=0,nd3=0,n1,n2,n3,c=0;
     long bin1=0,bin2=0,bin3=0,pval,b1,b2,b3;
     printf("\n Enter any number : ");
     scanf("%d %d",&num1,&num2);
      for(pval=1;num1!=0;num1/=2,pval*=10)
 bin1 += (num1%2)*pval;

      for(pval=1;num2!=0;num2/=2,pval*=10)
 bin2 += (num2%2)*pval;

     printf("\n\n Their Binary equivalents are : ");
     printf("%ld %ld",bin1,bin2);
     b1=bin1;
     b2=bin2;
     while(b1)
      {
b1/=10;
nd1++;
      }
     while(b2)
      {
b2/=10;
nd2++;
      }

     printf("\n\n Now , adding both these number in binary format ...");
     printf("\n\n %10ld \n +%9ld \n =",bin1,bin2);

    if( nd1>nd2 )
    {
      for(i=0;i<nd1;i++)
{
 n1=bin1%10;
 n2=bin2%10;
  if(c==0)
   {
     if( (n1==0 && n2==1) || (n2==0 && n1==1) )
{
  n3 = 1;
  c = 0;
}
     else if(n1==0 && n2==0)
{
  n3 = 0;
  c = 0;
}
     else
{
  n3 = 0;
  c = 1;
}
   }

  else
   {
    if( (n1==0 && n2==1) || (n2==0 && n1==1) )
{
  n3 = 0;
  c = 1;
}
     else if(n1==0 && n2==0)
{
  n3 = 1;
  c = 0;
}
     else
{
  n3 = 1;
  c = 1;
}

   }
 bin3 += (long) (n3*pow(10,i));
 bin1 /= 10;
 bin2 /= 10;
}
    }


    else
    {
      for(i=0;i<nd2;i++)
{
 n1=bin1%10;
 n2=bin2%10;
  if(c==0)
   {
     if( (n1==0 && n2==1) || (n2==0 && n1==1) )
{
  n3 = 1;
  c = 0;
}
     else if(n1==0 && n2==0)
{
  n3 = 0;
  c = 0;
}
     else
{
  n3 = 0;
  c = 1;
}
   }

  else
   {
    if( (n1==0 && n2==1) || (n2==0 && n1==1) )
{
  n3 = 0;
  c = 1;
}
     else if(n1==0 && n2==0)
{
  n3 = 1;
  c = 0;
}
     else
{
  n3 = 1;
  c = 1;
}
   }

 bin3 += (long)(n3*pow(10,i));
 bin1 /= 10;
 bin2 /= 10;
}
    }
    if(c==1)
     bin3 += pow(10,i);
    printf("%9ld",bin3);
    b3 = bin3;
    while(b3)
     {
       b3 /= 10;
       nd3++;
     }
    printf("\n\n The result is therefore : ");
    for(i=nd3;i>0;i--)
     {
       long x = pow(10,i-1);
       int y = bin3 / x;
       num3 += ( y * pow(2,i-1) );
       bin3 %= x;
     }
    printf("%d",num3);
    getch();
  }