`Math.trunc` vs `|0` vs `<<0` vs `>>0` vs `&-1` vs `^0`

限于喜欢 提交于 2019-11-29 11:00:30

How about Math.trunc(Math.pow(2,31)) vs. Math.pow(2,31) | 0

Bitwise operations are performed on signed 32-bit integers. So, when you do Math.pow(2, 31) you get this representation in bits "10000000000000000000000000000000". Because this number has to be converted to signed 32-bit form, we now have a 1 in the sign bit position. This means that we are looking at a -eve number in signed 32-bit form. Then when we do the bitwise OR with 0 we get the same thing in signed 32-bit form. In decimal it is -2147483648.

Side note: In signed 32-bit form the range of decimals that can be represented in binary for is [10000000000000000000000000000000, 01111111111111111111111111111111]. In decimal (base 10) this range is [-2147483648, 2147483647].

In many programming languages with bitwise operators, attempting to do a bitwise operation on a non-integer is a type error:

>>> # Python
>>> 1 << 0; 1.2 << 0
1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for <<: 'float' and 'int'

In ECMA-262, a Number is a double-precision 64-bit binary format IEEE 754. In other words, there are no integers in JavaScript. As long as the values you're dealing with fit within -(Math.pow(2,32)) and Math.pow(2,31) then the bitwise operations are a fast way to truncate floating point values. All of the different bitwise operations do different things, but in every example here they're essentially doing an identity operation. The critical difference is that JavaScript does a ToInt32 operation on the value before doing the nothing else part.

Bitwise identity operations:

i |  0 // For each bit that is 1, return 1|0. For each bit that is 0, return 0|0.
i ^  0 // xor, but effectively same as previous.
i << 0 // Shift the value left zero bits.
i >> 0 // Shift the value right zero bits.
i & -1 // Identity mask
~~i    // Not not - I had forgotten this one above.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!