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
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.
~
is the bitwise negation operator[MDN].3
in binary (using a 32-bit integer) isand
-3
in binary (using two's complement) isThe
~
operator reverses all of the1
s to0
s and all the0
s to1
, so~3
will bewhich is binary for
-4
(using two's complement).Similarly,
~-3
will bewhich is binary for
2
.3.346346
will be cast to an integer when doing bitwise operations, so it will have the same result as3
had.To sum up: