Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The meaning of Bit-wise NOT in Python [duplicate]

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.

like image 430
user25004 Avatar asked Oct 04 '17 20:10

user25004


Video Answer


1 Answers

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
like image 91
user2357112 supports Monica Avatar answered Oct 08 '22 12:10

user2357112 supports Monica