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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With