Why bitwise not does not act as expected for toggling bits? See for example below:
a = 5
print(bin(a))
b = ~a
print(bin(b))
This is the output:
0b101
-0b110
The question is why the first bit from the left is not toggled?
Considering that Python documentation says:
~ x Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1.
Edit: Are you saying that "~" is not the operator for simple toggling of bits, but instead it is the operator for twos complement? If so, why the sentence quoted from documentation does not tell that. The sentence above from Python documentation does not imply this to me.
It is toggling all the bits. All of them, including an infinite number of leading zeros, producing an infinite number of leading ones:
0b...111111111111111111111111111111111111111111111111111010
because Python simulates an infinite-bit representation, not 3-bit or 32-bit or 64-bit or any finite number. Quoting the docs,
The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits.
Python can't show you an infinite number of leading ones, so instead, it shows you bin(abs(b))
with a -
sign in front. abs(b)
is 6
and bin(6)
is '0b110'
, so you see
-0b110
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With