Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

bit manipulation - Javascript Tilde & Two's complement

Two's complement method - generates -(x + 1).

for example when JavaScript encounters the Tilde he uses this method:

~5 = -(5+1) = -6.

Fine - lets go deeper.

Now lets talk about the Two's complement method.

5        = 0000 0101
Flip     = 1111 1010
add one  = 1111 1011

so 1111 1011 is -5.

how ?

again : flip :

0000 0100 

add one :

0000 0101

And so it was -5.

So how does this settle with ~5=-6 ?

where this -6 came from ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all, you need to realize that ~ is the bitwise flip operator, which is not the same as the negate operator -. ~ does only do the bitwise flipping, but the negate operator - does bitwise flipping and add one (for integers).

As you've explained, if yo want to go from a postive number n to -n using the two complement method you bitwise flip/not n and add 1. ~n is just the bit-wise not meaning that ~n=-n-1.

For instance:

5               = 0000 0101
Flipped (~5)    = 1111 1010

So, which number does 1111 1010 represent? Since the first digit is a 1 we know it's a negative value. To find which value, do

-(flip(1111 1010) + 1) =
-(0000 0101 + 1)
-(0000 0110) =
-6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...