Skip to content Skip to sidebar Skip to footer

Javascript Right Shift A Negative Number

Here is the snippet: var i = 101; console.log('101: ' + i.toString(2)); console.log('101 >> 1: ' + (i >> 1).toString(2)); var l = -101; console.log('-101: ' + l.toStr

Solution 1:

Remember that negative numbers are stored as a 2s-complement. For simplicity, let's say it's a 1-byte signed integer, then -101 would be stored as

10000 0000(256)-0110 0101(101)=1001 1011(155ifitwereunsigned,-101insigned)

When bit-shifting a negative number, you right-pad with 1s instead of 0s (otherwise you'd lose the sign bit), so the result is:

1001 1011>>1=1100 1101

That is 205 if it were an unsigned integer. Then 2s-complement it back to solve 256 - x = 205 => x = 51

Ta-da? :D

Post a Comment for "Javascript Right Shift A Negative Number"