Python中~对布尔值的影响:为何~True=-2、~False=-1?
~True is -2 and ~False is -1 in Python Great question—this trips up a lot of people because it mixes up bitwise operations with boolean logic, plus Python's unique take on boolean values. Let's break this down step by step:
1. Booleans are just integers in Python
First, a key detail you might miss: in Python, bool is a subclass of int. That means:
Trueis exactly equivalent to the integer1(you can verify withTrue == 1→True)Falseis exactly equivalent to the integer0(checkFalse == 0→True)
This is why arithmetic works with booleans—True + 2 gives 3, and False * 5 gives 0. Bitwise operations like ~ treat them as integers, not just boolean flags.
2. What ~ (bitwise NOT) actually does
The ~ operator flips every bit in the binary representation of a number. But Python uses two's complement for signed integers, and since Python supports arbitrary-precision integers, the binary is effectively an infinite string of leading zeros for positive numbers.
A simpler way to calculate the result of ~x is using this formula:
~x = -x - 1
Let's apply this to your cases:
- For
~True(which is~1):-1 - 1 = -2 - For
~False(which is~0):-0 - 1 = -1
Why your initial reasoning was off
You tried using 2-bit binary, but Python doesn't limit integers to 2 bits. Let's look at the actual binary (simplified to 8 bits for clarity):
0(False) is00000000→ flipping all bits gives11111111, which is-1in 8-bit two's complement.1(True) is00000001→ flipping all bits gives11111110, which is-2in 8-bit two's complement.
Since Python uses arbitrary precision, the leading ones extend infinitely, but the result still maps to -1 and -2 respectively.
3. Why you don't get False/True in return
If you want to invert a boolean value logically, you need the not operator, not ~:
not True→Falsenot False→True
The ~ operator is a bitwise operation, not a logical one. It operates on the binary bits of the integer representation, so it returns an integer, not a boolean.
A note on the PyTables reference
The PyTables docs mentioning 8-bit booleans refers to how booleans are stored on disk in PyTables datasets, not how Python handles boolean values in memory. In Python's runtime, bool instances are still integer-based, so bitwise operations behave as we've explained.
内容的提问来源于stack exchange,提问作者zabop

