Amir Jalilifard
Amir Jalilifard

Reputation: 2059

Why ~N is doing -(N + 1) in JavaScript?

Look at the below examples please:

console.log(~-2); //1
console.log(~-1); //0
console.log(~0); //-1
console.log(~1); //-2
console.log(~2); //-3
console.log(~true); //-2
console.log(~false); //-1

Why ~N is operating like -(N + 1) ?

Upvotes: 2

Views: 457

Answers (6)

Silverspur
Silverspur

Reputation: 923

The ~ operator is the bitwise NOT operator. ~ takes the operand bit by bit and changes zeroes by ones and ones by zeroes.

~ (00010110)b = (11101001)b

Now, the negative integers are represented using Two's complement, which is exactly defined as executing bitwise NOT and adding one: then bitwise NOT is the same as negating the operand and substracting one:

 4 = (00000100)b
-4 = (11111100)b
-5 = (11111011)b = ~4

And you have the answer!

Upvotes: 4

Esteban
Esteban

Reputation: 2579

In JavaScript, ~ is the bitwise "flip" operator. That means it will invert the bit values of the binary representation of a value. It only accepts integer values, so it will coerce any value that you pass to an int.

An integer in JavaScript[1] is signed, and represented using the two's complement system. For instance (using 8 bits for simplicity):

2: 0000 0010

If we flip its bits we get

~2: 1111 1101

which is the binary representation (in two's complement) of -3, that's -(2+1), as you pointed out.

[1] which is actually represented as floating point number, but that just makes it more confusing, and can be disregarded for practical purposes.

Upvotes: 1

user2543253
user2543253

Reputation: 2173

~ is a binary not. It inverts a number's bits. All numbers in JavaScript are signed, so the first bit is always a sign bit. Therefore positive numbers become negative and vice versa. -1 because -1 is the inverse of zero. See also Bitwise operators at Mozilla

Upvotes: 1

user2191247
user2191247

Reputation:

When you convert to binary, it's easier to see what's happening:

 -1 → 11111111 11111111
~-1 → 00000000 00000000 →  0

  1 → 00000000 00000001
 ~1 → 11111111 11111110 → -2

Upvotes: 1

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

Because bitwise not works on the binary representation of the values. Take -5 for example, which is represented as:

1111 1111 1111 1111 1111 1111 1111 1011

in binary (32 bits)

Notting that value (flipping each bit from 1 to 0 or vice-versa) gives you:

0000 0000 0000 0000 0000 0000 0000 0100

Which is 4 in decimal.

Upvotes: 2

Krzysztof
Krzysztof

Reputation: 16140

It reverts all bits in number, and bit representation of integer number is as follows (for 3 bits numbers):

-4 = 100b
-3 = 101b
-2 = 110b
-1 = 111b
 0 = 000b
 1 = 001b
 2 = 010b
 3 = 011b

It works respectively for bigger numbers.

So by taking ~-2 you have ~(110b), which is equal to 001b and that is 1.

Upvotes: 4

Related Questions