DEV Community

Maroun Maroun
Maroun Maroun

Posted on

2

Why Does "~True" Result in -2 in Python?

If you try the following in your console:

~True

you'll get "-2" 😳. Why?

Think about bool, you'll find that it is numeric in nature - It can hold two values, "True" and "False", and they are just "customized" versions of the integers 1 and 0 that only print themselves differently.

So bool is a subclass of int:

>>> type(True)
<class 'bool'>
>>> isinstance(True, int)
True

>>> True == 1
True
>>> True is 1  # they're still different objects
False

Having that said, ~True evaluaes to:

~True == ~int(True) == ~1 == -2

~ simply flips the bits. So:

1  = 00000001
~1 = 11111110

which is -2 in two's complement. Verifying that:

Flip all the bits, add 1 to the resulting number and interpret the result as a binary representation of the magnitude and add a negative sign (since the number begins with 1):

11111110 → 00000001 → 00000010 
         ↑          ↑ 
       Flip       Add 1

Which is 2, but the sign is negative since the MSB is 1.

I hope that was clear :)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up