How to understand the demo of Right shift (>>)?

164 阅读2分钟

Prerequisites

Be familiar with the defination of Right shift (>>) and the mutual transformation between Binary and Decimal.

Demo

Demo1

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

The analysis steps:

  • 5 >> 2

    • 00000000000000000000000000000101 (base 2) -- 5 (base 10)
    • 00000000000000000000000000000001 (base 2) -- 1 (base 10) [5 >> 2]
  • -5 >> 2

    • 11111111111111111111111111111011 (base 2) -- -5 (base 10)
    • After >> 2, the intermediate number is 11111111111111111111111111111110 (base 2) -- Now, it boils down to how to transform this binary to decimal.
    • 00000000000000000000000000000001 (base 2)
    • 00000000000000000000000000000010 (base 2)
    • 1*2^1 + 0*2^0 = 2 + 0 = 2 (base 10)
    • -2 (base 10) ✅

Demo2

9 >> 2; //  2
-9 >> 2; // -3

The analysis steps:

  • -9 >> 2
    • 9 (base 10): 00000000000000000000000000001001 (base 2)
    • 11111111111111111111111111110110 (base 2)
    • 11111111111111111111111111110111 (base 2) i.e -9 (base 10)
    • After >> 2, the intermediate number is 11111111111111111111111111111101 (base 2)
    • 00000000000000000000000000000010 (base 2)
    • 00000000000000000000000000000011 (base 2)
    • 1*2^1 + 1*2^0 = 2 + 1 = 3 (base 10)
    • -3 (base 10)