Confusion on twos compliment in python

89 views Asked by At

So I tried the following in the python shell:

>>> x = -1
>>> x < 0
True
>>> x = -x
>>> x ^= 0xffffffff
>>> x += 1
>>> x < 0
False

So if i have a number thats initially negative, and i negate it and take the twos compliment, shouldnt it be negative again? why does python think the number is positive?

1

There are 1 answers

0
K.Suthagar On

You can check with your code using Print, You are making positive before that,

>>> x=-1
>>> x<0
True
>>> x=-x
>>> x
1
>>> x^=0xffffffff
>>> x
4294967294
>>> x+=1
>>> x
4294967295
>>> x<0
False

For more details, Just visit here https://wiki.python.org/moin/BitwiseOperators