4

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

Community
  • 1
  • 1
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

5

Because that's how Javascript represents negative numbers in binary. Docs:

The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format. Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all the number's bits inverted (bitwise NOT of the number, a.k.a. ones' complement of the number) plus one.

p4sh4
  • 3,292
  • 1
  • 20
  • 33