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

好久不见. 提交于 2020-08-19 11:59:05

问题


Doing some tests with bitwise operations / shifting with JavaScript

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

I would expect that to return 0x40000000 since

0x40000000 >> 1 // returns 0x20000000
0x20000000 >> 1 // returns 0x10000000

回答1:


Its an arithmetic shift that's why the sign is preserved, to do a logical shift use >>>

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



回答2:


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.



来源:https://stackoverflow.com/questions/14061999/why-does-0x80000000-1-in-javascript-produce-a-negative-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!