Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

According to subsection 11.4.8 of the ECMAScript 5.1 standard:

The production UnaryExpression : ~ UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Let oldValue be ToInt32(GetValue(expr)).
  3. 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:

  1. Let number be the result of calling ToNumber on the input argument.
  2. If number is NaN, +0, −0, +∞, or −∞, return +0.
  3. Let posInt be sign(number) * floor(abs(number)).
  4. 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.
  5. 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?

like image 346
user1039304 Avatar asked Aug 15 '13 17:08

user1039304


1 Answers

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.

like image 128
Hieu Le Avatar answered Sep 20 '22 14:09

Hieu Le