'Understanding Python's bitwise NOT
I was trying to understand bitwise NOT in python. I tried following:
>>> ~0b0
-1
>>> 0b1
1
Why is this the case? As per my understanding, ~0b0 is 0b1. But seems that python interprets it -1 in 2's complement, but 0b1 is getting interpreted as 1.
Why is this so? More importantly, how and why does python determines when to interpret number or MSB of binary string negative?
Solution 1:[1]
Python interprets a word of binary bits as a negative number when
a) the sign bit is set (the most significant bit of a word)
and
b) the str or repr method is called (to get the string representation or value representation of a word).
or, implicitly, any time you treat the word as a number.
Solution 2:[2]
Per-spec:
The unary
~(invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion ofxis defined as-(x+1).
because semantically Python's integers are always signed and manipulated as two's complement.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Masklinn |
