To answer this question, I have to explain about Two's Complement.
BINARY REPRESENTATION OF NUMBERS
So you know how internally, an integer like 5 is represented as a binary string
00000000000000000000000000000101
How do you imagine you'd represent a negative number?
Well, here's what we want to do:
Addition should work the same with negative numbers and positive numbers; i.e. you do the same steps to add 4 + 9 as 4 + -9.
Integer overflow shouldn't break mathematics; i.e. MAX_VALUE + 1 == MIN_VALUE
, MIN_VALUE - 1 == MAX_VALUE
So what we do is called "Two's Complement."
TWO'S COMPLEMENT
To represent a negative number, take its absolute value, bitflip every bit, and add 1.
So if the positive number is 5
00000000000000000000000000000101
the negative number -5 is
11111111111111111111111111111011
Essentially, this means we pick the number 01111111111111111111111111111111
to be the largest positive number, and all numbers after that are negative.
SO WHAT DOES (5 | -2) MEAN?
The |
is the bitwise or operator. Given two numbers, it takes every bit and or's them together, constructing a new number where a digit is 1 if the digit in that position in wither or both of the two original numbers is 1, and 0 otherwise. The calculation looks like this:
5 -> 00000000000000000000000000000101
| -2 -> 11111111111111111111111111111110
---- --------------------------------
11111111111111111111111111111111 -> -1
So as you can see, 5 | -2 = -1 < 0.
WHAT ABOUT (5 or -2)?
The "or" operator takes two values, casts them to booleans and or's them together. This is important: it doesn't or the values, it returns the first value that is "truthy" -- in other words, if you put it in an if statement, it would run.
The only integer that isn't "truthy" is 0. Therefore (5 or -2) returns the first non-zero integer of 5 and 2, which is 5 > 0. So 5 or -2 = 5 > 0.