Infinite loop while adding two integers using bitwise operations in Python 3 -
i trying solve question writing python code adding 2 integers without use of '+' or '-' operators. have following code works 2 positive numbers:
def getsum(self, a, b): while (a & b): x = & b y = ^ b = x << 1 b = y return ^ b this piece of code works if input 2 positive integers or 2 negative integers fails when 1 number positive , other negative. goes infinite loop. idea why might happening ?
python 3 has arbitrary-precision integers ("bignums"). means anytime x negative, x << 1 make x negative number twice magnitude. zeros shifting in right push number larger , larger.
in two's complement, positive numbers have 0 in highest bit , negative numbers have 1 in highest bit. means that, when 1 of a , b negative, top bits of a , b differ. therefore, x positive (1 & 0 = 0) , y negative (1 ^ 0 = 1). new a positive (x<<1) , new b negative (y).
now: arbitrary-precision negative integers have infinite number of leading 1 bits, @ least mathematicallly. a larger , larger positive number, expanding 2 each iteration. b keeps getting more , more leading 1 bits added able carry out bitwise & , ^ a. whatever bits of a turned on line 1 of added 1 bits of b, a & b true, loop runs forever.
Comments
Post a Comment