Can someone explain why Javascript gives the following results?
~3 = -4
~3.346346 = -4
~-3 = 2
Can someone explain why Javascript gives the following results?
~3 = -4
~3.346346 = -4
~-3 = 2
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 = -4The 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.
~is the bitwise negation operator[MDN].3in binary (using a 32-bit integer) isand
-3in binary (using two's complement) isThe
~operator reverses all of the1s to0s and all the0s to1, so~3will bewhich is binary for
-4(using two's complement).Similarly,
~-3will bewhich is binary for
2.3.346346will be cast to an integer when doing bitwise operations, so it will have the same result as3had.To sum up: