Negation in JavaScript

553 views Asked by At

Can someone explain why Javascript gives the following results?

~3 = -4
~3.346346 = -4
~-3 = 2
2

There are 2 answers

0
Peter Olson On BEST ANSWER

~ is the bitwise negation operator[MDN].

3 in binary (using a 32-bit integer) is

0000 0000 0000 0000 0000 0000 0000 0011 (3)

and -3 in binary (using two's complement) is

1111 1111 1111 1111 1111 1111 1111 1101 (-3)

The ~ operator reverses all of the 1s to 0s and all the 0s to 1, so ~3 will be

1111 1111 1111 1111 1111 1111 1111 1100 (~3 == -4)

which is binary for -4 (using two's complement).

Similarly, ~-3 will be

0000 0000 0000 0000 0000 0000 0000 0010 (~-3 == 2)

which is binary for 2.

3.346346 will be cast to an integer when doing bitwise operations, so it will have the same result as 3 had.


To sum up:

  3 = 0000 0000 0000 0000 0000 0000 0011 = (int)3.346346
 ~3 = 1111 1111 1111 1111 1111 1111 1100 = -4
 -3 = 1111 1111 1111 1111 1111 1111 1101
~-3 = 0000 0000 0000 0000 0000 0000 0010 =  2
0
Stefano Sanfilippo On

This is because negative numbers are stored as two's complement:

minusB = ~B + 1;

In your case, reversing the formula above:

  • -3 is stored as ~3 + 1. So, ~-3 is equivalent to -(-3) - 1 = 2.
  • ~3.346346 is first rounded to 3, then ~3 can be read as -3 - 1 = -4

The reason why two's complement is used (instead of using a separate bit for sign), is that it makes subtraction and addition trivial, regardless of signs.