Afshin Mehrabani - 10 months ago 52

Javascript Question

Suppose we have

`1`

`00000000000000000000000000000001`

Now I want to flip all bits to get following result:

`11111111111111111111111111111110`

As far as I know, the solution is to use the

`~`

`~1`

`-2`

`console.log(~1); //-2`

console.log((~1).toString(2)); //-10 (binary representation)

Why do I get this strange result?

Answer

There are 2 integers between `1`

and `-2`

: `0`

and `-1`

`1`

in binary is `00000000000000000000000000000001`

`0`

in binary is `00000000000000000000000000000000`

`-1`

in binary is `11111111111111111111111111111111`

`-2`

in binary is `11111111111111111111111111111110`

^{("binary" being 2's complement, in the case of a bitwise not ~ )}

As you can see, it's not very surprising `~1`

equals `-2`

, since `~0`

equals `-1`

.

As @Derek explained, These bitwise operators treat their operands as a sequence of 32 bits. `parseInt`

, on the other hand, does not. That is why you get some different results.