Why does 0x80000000 >> 1 in JavaScript produce a negative value?

后端 未结 2 1560
日久生厌
日久生厌 2021-01-18 17:45

Doing some tests with bitwise operations / shifting with JavaScript

0x80000000 >> 1 // returns -1073741824 (-0x40000000)

I would expe

2条回答
  •  情深已故
    2021-01-18 18:21

    In Javascript, >> is the Signed Right Shift Operator. In §11.7.2 of the language specification it says:

    Performs a sign-filling bitwise right shift operation on the left operand by the amount specified by the right operand.

    Before the shifting is done, the left operand is converted to a signed 32-bit integer (step 5 of the algorithm given in the specification). In your case this conversion turns the given positive number into a negative value. After that, the actual shifting is done, preserving the negative sign of the value.

提交回复
热议问题