2

In Javascript when I do this

var num = 1;

~ num == -2

why does ~num not equal 0

in binary 1 is stored as 1 ... thus not 1 should be 0

or it is stored like 0001 thus not 0001 would be 1110

I think I am missing something... can someone clear this up

samccone
  • 10,746
  • 7
  • 43
  • 50

4 Answers4

5

Look up Two's complement for signed binary numbers

Lets assume that a javascript Number is 8 bits wide (which its not):

then

1 = 0000 0001b

and

~1 = 1111 1110b

Which is the binary representation of -2

0000 0010b =  2
0000 0001b =  1
0000 0000b =  0
1111 1111b = -1
1111 1110b = -2
J. Holmes
  • 18,466
  • 5
  • 47
  • 52
2

~ toggles the bits of the operand so

00000001

becomes

11111110

which is -2

Note: In javascript, the numbers are 32-bit, but I shortened it to illustrate the point.

Dennis
  • 32,200
  • 11
  • 64
  • 79
1

From the documentation:

Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

The reason for this is that using a bitwise NOT reverses all the bits of a value. If you are storing the value of 1 in a signed 8-bit integer, you're storing the binary value 00000001. If you apply a bitwise NOT, you get 11111110, which for a signed 8-bit integer is the binary value for -2.

Raider
  • 740
  • 6
  • 11