Jaf-2017
Jaf-2017

Reputation: 89

How does JavaScript's Bit-wise operation deals with NOT (~) operation?

Executing the following lines of code in JavaScript always produce unexpected result, which I do not have any clue with. This is how I perform a NOT (invert) operation:

2 = 0010

(~ 2) = 1101, which is 13 in decimal. But performing this exact same operation in JavaScript outputs the value -3. Can anyone explain why so?

<body>
    <p id="demo"></p>
    <script>
    document.getElementById("demo").innerHTML = ~ 2;
    </script>
    </body>

Result: -3

Upvotes: 2

Views: 61

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234795

JavaScript uses two's complement representation for integer values. It also performs all bitwise operations on signed, 32-bit integers (converting arguments as necessary). So the expression ~2 does not result in 1101; instead it is

1111 1111 1111 1111 1111 1111 1111 1101

which happens to be the two's complement representation of -3. (The leftmost bit being 1 indicates a negative number.)

Consult the docs on bitwise operators for more info.

P.S. If you really want a result of 13, you can mask out all but the lower four bits: ((~2) & 0xF).

Upvotes: 6

Dinesh undefined
Dinesh undefined

Reputation: 5546

It is a unary operator that takes the expression to its right performs this small algorithm on it (where N is the expression to the right of the tilde): -(N+1)

For example ~2 produces -3

Upvotes: 0

Related Questions