0

Intuitively, I would think ~True would return False, since ~ is the bitwise "not" operator, but this obviously isn't the case. What is really going on here, and how do I get -2 as a return value?

In [0]: ~True                                                                                      
Out[0]: -2

In [1]: ~False                                                                                     
Out[1]: -1
DanDy
  • 451
  • 5
  • 10
  • 1
  • 2
    Bitwise means as in binary. As in numbers. – theX Jul 15 '20 at 18:55
  • 1
    `~` is negating *all* of the bits, not just the lowest one. – jasonharper Jul 15 '20 at 18:56
  • 2
    `~1 == 2` "~ x : Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1. " – Cagri Jul 15 '20 at 18:56
  • 1
    See [Two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) – khelwood Jul 15 '20 at 18:58
  • 1
    If you want to reverse the boolean value, you would use the `not` operator – Niko Föhr Jul 15 '20 at 19:15
  • 1
    `~` is a bitwise not operator. You can see what's happening with `bin(True) => '0b1'` (binary notation of `True`), and `bin(~True) => -0b10` (shows that `~True` is the two's complement of `True`). – lseki Jul 15 '20 at 19:19
  • This is an unexpected side effect of the `bool` type being a subclass of `int`. You would naturally expect bools to be represented by a single bit, but they are treated as if they have an infinite number of bits the same as any other integer. – Mark Ransom Jul 05 '22 at 17:43

0 Answers0