简体   繁体   中英

Why does ~False give -1 and ~True -2?

I always thought that ~ was equivalent to not in Python, but I had a bug that made me find out this. Could someone explain to me what that is?

Thanks

From the official documentation :

The unary ~ (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of x is defined as -(x+1) . It only applies to integral numbers.

As to why ~False would be -1 , it's because for historical reasons False == 0 and True == 1 (they're not identical but they are equal, and bool is a subclass of int ). If you apply the formula above, you get ~False => -(False + 1) => -(0+1) => -1 , QED.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM