2023-W16 Wendland Weekly
Why is ~10 = -11 in python?
Well what is ~10?
The ~
is a bitwise operation in Python. To be exact, it is the bitwise not operator. This means that it takes the binary representation of the provided number and flips all the 1’s to 0’s and vice versa.
Ok … then what is the binary representation of 10?
In Python Index, integers are stored as signed integers using the Two’s complement representation. In fact, Python is even more complicated because integers are dynamically sized as well. For our sake, let’s just say it is stored in a byte of 8 bits. So, 10’s byte representation would be 0000 1010
.
So then we have 1111 0101… what number does this represent in Two’s complement… and don’t just say -11.
Well, 1111 0101
is negative (the most significant digit which for us is to the left is 1), so you need to do some work to find the decimal representation. First, subtract 1, giving 1111 0100
. Then, flip the digits to 0000 1011
. Lastly, we use that basic binary representation, but with a minus sign in front of it… i.e. (-) 8 + 2 + 1 = -11.
Ahh ok, well don’t you feel smart. Seems like a lot of effort for something so minor.
There is an easier way to think about this operation. For positive numbers (of which 0 is one), we start from 0 and carry on up to as much as your memory can take. Whereas for negative numbers, we start at -1 and continue down. The bitwise not operation in the Two’s complement representation switches a number between positive and negative but keeps its relative position in the index. So, ~4 = -5
or ~(-7) = 6
.
Nice… well, that was a fun hole you got yourself into trying to work out why a ^ b ^ c returns the third element if two of them are the same. Congrats, Alex… you lost another evening.