Infinite loop while adding two integers using bitwise operations?
Python 3 has arbitrary-precision integers ("bignums"). This means that anytime x
is negative, x << 1
will make x
a negative number with twice the magnitude. Zeros shifting in from the right will just push the number larger and larger.
In two's complement, positive numbers have a 0
in the highest bit and negative numbers have a 1
in the highest bit. That means that, when only one of a
and b
is negative, the top bits of a
and b
will differ. Therefore, x
will be positive (1 & 0 = 0
) and y
will be negative (1 ^ 0 = 1
). Thus the new a
will be positive (x<<1
) and the new b
will be negative (y
).
Now: arbitrary-precision negative integers actually have an infinite number of leading 1
bits, at least mathematicallly. So a
is a larger and larger positive number, expanding by 2 each iteration. b
keeps getting more and more leading 1
bits added to be able to carry out the bitwise &
and ^
with a
. Thus whatever bits of a
are turned on line up with one of the added 1
bits of b
, so a & b
is always true, so the loop runs forever.