1/12: What is ~ (not)


#1

I don't know what the ~ (not) symbol does. I looked it up and it said: inverting its value such that all zeros are turned into ones and all ones are turned to zeros. Why would it make the number negative?
In the lesson it said that ~88 = -89.

Help!


#2

It's a bitwise operator, so we have to treat numbers as lists of single bits. Python uses two's complement representation of binary signed numbers.

In this representation, the most significant bit represents not only the value but also a sign of the number. 0 - positive number, 1 - negative number. So after a bitwise negation (~) number changes its sign.

We count value of the number as normally -> the weight of each bit is a power of two, except for the most significant bit, whose weight is the negative of the corresponding power of two.

Let's assume that we are working on 8 bits, ok?

 88 = 0101 1000 
~88 = 1010 0111 = 1 + 2 + 4 + 32 - 128 = 39 - 128 = -89

#3

thanks! That really helps


#4

Great! You're very welcome :panda_face: