5

I found that ~True is -2 and ~False is -1. Why is this?

W3Schools says that ~ inverts 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 paints a more complicated picture:

A list full of Trues only contains 4- or 8-byte references to the one canonical True object.

The PyTables User’s Guide says:

bool: Boolean (true/false) types. Supported precisions: 8 (default) bits.

These don't support the simplistic (and apparently wrong) reasoning above.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
zabop
  • 6,750
  • 3
  • 39
  • 84

1 Answers1

7

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Ronald
  • 2,842
  • 16
  • 16
  • Would you add some details on why 1111 1110 is -2? As I understand 1110 is 2, but why? why not 0010 is 2? – zabop Aug 19 '20 at 10:17
  • 1
    @zabop `0010` *is* 2. `1110` is **minus** 2, if you only have four bits and you're using [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement). – jonrsharpe Aug 19 '20 at 10:19
  • 1
    In two's complement inverting the sign involves: "flip the bits and add 1". If the first bit is set, the number is negative, else positive. Now let me try this with 1110. The first bit is set (where first is the leftmost bit in this case), thus it is negative. The positive number is then (flip the bits and add one) 0001 + 1 = 0010 ( = 2 in decimal representation) – Ronald Aug 19 '20 at 10:33