Here is the explanation of why ~5
equals to -6
from here:
5 = 0000 0101
Flipped (~5) = 1111 1010
So, which number does 1111 1010 represent? Since the first digit is a 1 we know it's a negative value. To find which value, do
-(flip(1111 1010) + 1) = -(0000 0101 + 1) -(0000 0110) = -6
I'm wondering why Javascript treats the result of the ~5
as a number in the two's complement form?
My confusion stems from the fact that if I write 0b11111010
in the console it evaluates to 250, not -6