I understand bitwise addition, and I understand bitwise operations, but I'm having a hard time understanding why this code effectively adds two integers.
def Add(x, y):
while (y != 0):
carry = x & y
x = x ^ y
y = carry << 1
return x
Is there someone that can please provide an intuitive explanation for exactly why this works? I can follow the logic for the right most bit initially. I..e, it makes sense that the carry item should be the result of and operation between x and y on the right most bit. Then, we use the left shift to make that carry computed at the first iteration on the right most bit now apply to the second right most bit on the second iteration. Around this point that I start getting quite confused (i.e., because the new "y" on iterations > 1 are the result of the previous carry operation, etc).
If someone who understands this in depth can break it down, I'd appreciate it.