Why a positive number operated with bitwise or 0 not always positive in Javascript

为君一笑 提交于 2019-12-13 14:26:29

问题


Why a positive number operated with bitwise or 0 not always positive in Javascript

For example:

3391700000|0
-903267296

4260919000|0
-34048296

2884900000|0
-1410067296

I'm using chrome 64-bit on Linux

related to: https://stackoverflow.com/a/12837315/1620210


回答1:


Because JavaScript uses 32bit integers at most, but keep in mind every number is kind of a float in this language

If you want to truncate them to an unsigned 32bit value:

(3391700000|0) >>> 0



回答2:


In JavaScript, the operands of bitwise operators are converted to signed 32-bit integers in 2's complement format. Thats why you got some loss of data and the truncated values are sometimes negative because of signed two's complement representation.

You can refer to Why bitwise shift with 0 in JavaScript yields weird results in some cases thread which was asked by myself some time ago and some answers pointed out the possible issue with bitwise operators where your operands exceed 32-bit integers very comprehensively.



来源:https://stackoverflow.com/questions/31337785/why-a-positive-number-operated-with-bitwise-or-0-not-always-positive-in-javascri

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