javascript - Why does ~-1 equal 0 and ~1 equal -2? -
according subsection 11.4.8 of ecmascript 5.1 standard:
the production unaryexpression : ~ unaryexpression evaluated follows:
- let
expr
result of evaluating unaryexpression.- let
oldvalue
toint32(getvalue(expr))
.- return result of applying bitwise complement
oldvalue
. result signed 32-bit integer.
the ~
operator invoke internal method toint32
. in understanding toint32(1)
, toint32(-1)
return same value 1 , why ~-1
equal 0 , ~1
equal -2?
now question why toint32(-1)
equals -1? subsection 9.5 of ecmascript 5.1 standard:
the abstract operation toint32 converts argument 1 of 232 integer values in range −231 through 231−1, inclusive. abstract operation functions follows:
- let number result of calling tonumber on input argument.
- if number nan, +0, −0, +∞, or −∞, return +0.
- let posint sign(number) * floor(abs(number)).
- let int32bit posint modulo 232; is, finite integer value k of number type positive sign , less 232 in magnitude such mathematical difference of posint , k mathematically integer multiple of 232.
- if int32bit greater or equal 231, return int32bit − 232, otherwise return int32bit.
when argument -1,according 9.5, in step 1 number still -1, skip step2 in step 3 posint -1 in step 4 int32bit 1 in step 5 return 1
which step wrong?
the -1
in 32-bit integer
1111 1111 1111 1111 1111 1111 1111 1111
so ~-1
be
0000 0000 0000 0000 0000 0000 0000 0000
which zero.
the 1
in 32-bit integer
0000 0000 0000 0000 0000 0000 0000 0001
so ~1
be
1111 1111 1111 1111 1111 1111 1111 1110
which -2
.
you should read two's complement understand display of negative integer in binary-base.
Comments
Post a Comment