Showing posts with label adder logic. Show all posts
Showing posts with label adder logic. Show all posts

Tuesday, December 31, 2013

AND and XOR Gate : Addition without using + sign

Have you ever wondered how does a computer do addition operation. It doesn't have any fingers on which it can count on like little kids do.

AND and XOR logic gates help computer to do addtion

Rules for addition for binary numbers
0 + 0 = 0
1 + 0 = 1
0 + 1 = 1
1 + 1 = (1 carry over) 0

add 17 + 5
17 = 1 0 0 0 0 1
  5 = 0 0 0 1 0 1
---------------------
22 = 1 0 0 1 1 0

Truth table for XOR
x      y         x XOR y
0      0            0
0      1            1
1      0            1
1      1            0

We can see that addition of bits have similar behavior as XORing the two bits
To see whether there is a carry over we  need AND gate

Truth table for AND
x      y         x AND y
0      0            0
0      1            0
1      0            0
1      1            1

In C language ^ operator is bitwise XOR and & operator is bitwise AND
<< is the left shift operator
011010<<1 =110100 [each digit is shifted to left side and to the right a 0 digit is added] 

Addition without arithmetic operator +
Steps
1. sum = x XOR y
2. carry = x AND y
3. carry = carry << 1
4. x = sum
5. y = carry
6. Goto Step 1 if carry is not equal to 0.
7. If carry equal to 0 print sum

Example
let x = 15 = 1 1 1 1
let y =   9 = 1 0 0 1
sum  x^y =  0 1 1 0
carry x&y= 1 0 0 1

carry<<1 = 1 0 0 1 0 (carry not equal to 0, loop to begining)

x=sum         0 0 1 1 0
y=carry       1 0 0 1 0
sum x^y=    1 0 1 0 0
carry x&y=  0 0 0 1 0

carry<<1 =  0 0 1 0 0 (carry not equal to 0, loop to begining)

x=sum         1 0 1 0 0
y=carry       0 0 1 0 0
sum x^y=    1 0 0 0 0
carry x&y=  0 0 1 0 0

carry<<1 =  0 1 0 0 0 (carry not equal to 0, loop to begining)

x=sum         1 0 0 0 0
y=carry       0 1 0 0 0
sum x^y=    1 1 0 0 0
carry x&y=  0 0 0 0 0

carry<<1 =  0 0 0 0 0 (carry = 0 , go out of loop)

print sum = 1 1 0 0 0 = 24

#include<stdio.h>
int main()
{
    int x,y,sum, carry;
    int xcopy,ycopy;
    printf("\nEnter the two numbers:");
    scanf("%d%d",&x,&y);
    xcopy=x;
    ycopy=y;

    do
        {
         sum=x^y;
         carry=x&y;
         carry=carry<<1;
         x=sum;
         y=carry;
        }while(carry!=0);

      printf("%d + %d = %d", xcopy, ycopy, sum);
      return 0;
}