You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中~对布尔值的影响:为何~True=-2、~False=-1?

Why ~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:

  • True is exactly equivalent to the integer 1 (you can verify with True == 1 → True)
  • False is exactly equivalent to the integer 0 (check False == 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) is 00000000 → flipping all bits gives 11111111, which is -1 in 8-bit two's complement.
  • 1 (True) is 00000001 → flipping all bits gives 11111110, which is -2 in 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 → False
  • not 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 22:02:49