samccone
samccone

Reputation: 10926

javascript bitwise operator question

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

Upvotes: 2

Views: 274

Answers (4)

Raider
Raider

Reputation: 750

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.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

From the documentation:

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

Upvotes: 1

Dennis
Dennis

Reputation: 32598

~ 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.

Upvotes: 2

J. Holmes
J. Holmes

Reputation: 18546

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

Upvotes: 5

Related Questions