wtfpython icon indicating copy to clipboard operation
wtfpython copied to clipboard

Why does ~True evaluate to -2 ?

Open lcrmorin opened this issue 2 years ago • 3 comments

I don't see it in the list. Working in a jupyter notebook ~True evaluates to -2. ( ~np.array(True) correctly evaluates to False).

Can someone explain the answer ? Does it need to be added in the list ?

lcrmorin avatar Jun 04 '22 08:06 lcrmorin

Thanks for the suggestion.

~ is a bitwise NOT operator, which essentially inverts all the 1s and 0s in the binary representation of the operand. The int value of True is 1. So essentially what you're seeing is ~1, which is -2. Why ~1 is -2 needs a bit tricky to explain. The negative numbers are internally represented as two's complement, and when you apply the ~, by flipping the bits, you end up exactly at the binary representation of -2. This StackOverflow thread explains it to some extent https://stackoverflow.com/a/12946226/4354153

I think this would be a good addition to the collection (if someone's up for the challenge, most welcome :), otherwise I'll add it in next major revision) because it's sometimes tempting to use ~ in the boolean conditional logic but it can lead to confusing results like

>>> True == ~False
False

and of course also because numpy handles it differently as you suggested (need to look deeper into it).

satwikkansal avatar Jun 04 '22 15:06 satwikkansal

Thanks for the explanation. This is frightening as I might have used this before...

lcrmorin avatar Jun 04 '22 15:06 lcrmorin

thank you, this is interesting :)

>>> ~True
-2

>>> ~False
-1

>>> ~True + ~False
-3

and I didn't know you can even add True to integer:

>>> 5 + True
6

jablka avatar Dec 21 '22 09:12 jablka