Monday, May 24, 2010

Please explain it in words?

int add(int a, int b)








{


int c = 0;


int sum = 0;


int i = -1;


**************************************...


while (++i %26lt; 32) {//considered arihmatic? :D


//sum = a XOR b XOR c


sum |= ((c %26amp; 1) ^ (a %26amp; 1) ^ (b %26amp; 1)) %26lt;%26lt; i;





//cout - (A AND B) OR (Cin AND (A XOR B))


c = (((a %26amp; 1) %26amp; (b %26amp; 1)) + ((c %26amp;1) %26amp; ((a %26amp;1) ^ (b %26amp;1))))? 1 : 0;





a = a %26gt;%26gt; 1;


b = b %26gt;%26gt; 1;


**************************************...


}





return sum;


}





This is the example for addition without using arithmetic operator.


Respected I want to know theoretical description of the statements which are present between the layers of "*********". I mean I want to know that what these statements do in real. I will be thankful to you for this kindness.

Please explain it in words?
This code is doing the addition a binary digit (bit) at a time.





sum |= ((c %26amp; 1) ^ (a %26amp; 1) ^ (b %26amp; 1)) %26lt;%26lt; i;


The line above takes the least significant bit (that's the %26amp; 1 parts) of c and a and b, and xors them together. So if c (the carry) is 0, then if either a or b is a 1 and the other is 0 the result will be a 1, otherwise it will be a 0. If there's a carry and we would had a 1, it becomes a 0, if it was a 0, it will be a 1. Once we've calculated what that bit will be, we shift it up by the number of bits we've processed so far (the %26lt;%26lt; i), and or it into the sum.





c = (((a %26amp; 1) %26amp; (b %26amp; 1)) + ((c %26amp;1) %26amp; ((a %26amp;1) ^ (b %26amp;1))))? 1 : 0;


This line is calculating the carry to move forward to the next iteration. Basically, there is a carry if two or more of the three bits are set. This code basically says if both a and b bits are set, or if either of a and b are set and the c bit is also set, then we'll have a carry for the next binary digit





finally, the lines


a = a %26gt;%26gt; 1;


b = b %26gt;%26gt; 1;


shift down the original numbers by one bit so that the next higher bit in the original number is now the least significant bit so that the next iteration through the code will operate on the next bit up.





This whole process is repeated 32 times, controlled by the while loop to add all the bits of the 32 bit number one at a time.


No comments:

Post a Comment