Why does ~-1 equal 0 and ~1 equal -2?

bitwise-operators, ecmascript-5, javascript, operators

Solution

The `-1` in 32-bit integer

1111 1111 1111 1111 1111 1111 1111 1111

So `~-1` will be

0000 0000 0000 0000 0000 0000 0000 0000

Which is zero.

The `1` in 32-bit integer

0000 0000 0000 0000 0000 0000 0000 0001

So `~1` will be

1111 1111 1111 1111 1111 1111 1111 1110

Which is `-2`.

You should read about two's complement to understand the display of negative integer in binary-base.

Problem

According to subsection 11.4.8 of the ECMAScript 5.1 standard: The production UnaryExpression : ~ UnaryExpression is evaluated as follows: - Let `expr` be the result of evaluating UnaryExpression. - Let `oldValue` be `ToInt32(GetValue(expr))`. - Return the result of applying bitwise complement to `oldValue`. The result is a signed 32-bit integer. The `~` operator will invoke the internal method `ToInt32`. In my understanding `ToInt32(1)` and `ToInt32(-1)` will return the same value 1 , but why does `~-1` equal 0 and `~1` equal -2? Now my question is why `ToInt32(-1)` equals -1? subsection 9.5 of the ECMAScript 5.1 standard: The abstract operation ToInt32 converts its argument to one of 232 integer values in the range −231 through 231−1, inclusive. This abstract operation functions as follows: - Let number be the result of calling ToNumber on the input argument. - If number is NaN, +0, −0, +∞, or −∞, return +0. - Let posInt be sign(number) * floor(abs(number)). - Let int32bit be posInt modulo 232; that is, a finite integer value k of Number type with positive sign and less than 232 in magnitude such that the mathematical difference of posInt and k is mathematically an integer multiple of 232. - If int32bit is greater than or equal to 231, return int32bit − 232, otherwise return int32bit. when the argument is -1,according to 9.5, in step 1 number will still be -1, skip step2 in step 3 posInt will be -1 in step 4 int32bit will be 1 in step 5 it will return 1 which step is wrong?

Original source