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

后端 未结 2 1002
梦谈多话
梦谈多话 2020-12-19 08:16

I have just found that in ES6 there\'s a new math method: Math.trunc.

I have read its description in MDN article, and it sounds like using |0

2条回答
  •  旧巷少年郎
    2020-12-19 08:17

    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].

提交回复
热议问题