wongx
wongx

Reputation: 11927

How does -5 >> 2 === -2?

In the MDN docs, there is this example below under right shift operator.

const a = 5;          //  00000000000000000000000000000101
const b = 2;          //  00000000000000000000000000000010
const c = -5;         // -00000000000000000000000000000101

console.log(a >> b);  //  00000000000000000000000000000001
// expected output: 1

console.log(c >> b);  // -00000000000000000000000000000010
// expected output: -2

5 >> 2 makes sense because you shift the digits right 2 spaces. In the second example of -5 >> 2, why does it only seemingly shift to the right one space even though it's >> 2?

MDN Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift

Upvotes: 0

Views: 70

Answers (1)

Tkun
Tkun

Reputation: 69

Just like Johnny side, you might want to check the Two's complement rule. The number in left most might be 1 inside of 0. You might want to check the example with -9 this example will help you understand better.

Upvotes: 2

Related Questions