Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ~True = -2 in python?

I am completely perplexed. We came across a bug, which we easily fixed, but we are perplexed as to why the value the bug was generating created the output it did. Specifically:

Why does ~True equal -2 in python?

~True 
>> -2 

Shouldn't the bitwise operator ~ only return binary?

(Python v3.8)

like image 902
WolVes Avatar asked Dec 08 '25 06:12

WolVes


1 Answers

True is a specialization of int. In python, integers are signed and unbounded. If one were to invert a fixed-size integer like the 16 bit 0x0001, you'd get 0xfffe which is -2 signed. But python needs a different definition of that operation because it is not size bounded. In Unary arithmetic and bitwise operations python defines unary inversion as

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 or to custom objects that override the invert() special method.

This has the same effect as fixed-size bit inversion without messing around with infinity. Sure enough

>>> -(True+1)
-2
like image 184
tdelaney Avatar answered Dec 09 '25 19:12

tdelaney