问题
The problem
I found that ~True
is -2
& ~False
is -1
using my Jupyter Notebook.
This source says that ~
invertes all the bits. Why isn't ~True
is False
and ~False
is True
?
Reasoning attempts
My attempt to explain these:
True
is +1
, and the bits of +1
are inverted. +
is inverted to -
.
1
in two-digit binary is 01
, so inverted bits: 10
, ie 2
. So result is -2
.
False
is +0
, +
is inverted to -
, 0
in two-digit binary is 00
, all the bits inverted, 11
, which is 3
- it should be 1
.
Sources
This answer points a more complicated picture:
A list full of Trues only contains 4- or 8-byte references to the one canonical True object.
This source says:
bool: Boolean (true/false) types. Supported precisions: 8 (default) bits.
These don't support the simplistic (and apparently wrong) reasoning above.
The question
What is the proper explanation for ~True
being -2
& ~False
being -1
then?
回答1:
First of all, I'd use the not operator to invert Boolean values (not True == False, and vice versa). Now if Booleans are stored as 8-bit integers, the following happens:
True is 0000 0001. Hence ~True yields 1111 1110, which is -2 in two's-complement representation.
False is 0000 0000. Hence ~False yields 1111 1111, which is -1.
来源:https://stackoverflow.com/questions/63484690/effect-of-tilde-on-booleans-why-true-is-2-false-is-1-in-python