0

In Javascript, if I do the bitwise NOT operation on the decimal integer 10:

~10

I expect it to compute bitwise NOT on the binary integer as follows:

~1010 = 0101

In otherwords, I expected decimal integer 5. Instead, the operation gives me -11. (try it in your console)

~10 = -11

If I check that more explicitly by looking at -11 and ~10 as binary integer strings:

parseInt(~10,10).toString(2)
"-1011"

parseInt(-11,10).toString(2)
"-1011"

Consistent. But I don't understand. Can anyone explain to me why? I'm guessing that it is something to do with the sign.

EDIT: I found this question after posting, it also helped me understand this phenomena much better.

Community
  • 1
  • 1
msolters
  • 225
  • 2
  • 8

1 Answers1

4

Bitwise operators in Javascript treat the number as 32 bits. So 10 is

00000000 00000000 00000000 00001010

When you invert it, the result is:

11111111 11111111 11111111 11110101

When interpreted as a 32-bit signed number, that's -11 (if you don't understand why, read the Wikipedia entry on Two's Complement).

Barmar
  • 741,623
  • 53
  • 500
  • 612