右移 >> 将值变为零 javascript

right shift >> turns value into zero javascript

尝试在 javascript 中进行一些位操作。

考虑以下几点:

const n = 4393751543811;
console.log(n.toString(2)) // '111111111100000000000000000000000000000011'
console.log(n & 0b11) // last two bits equal 3
const m = n >> 2; // right shift 2
// The unexpected.
console.log(m.toString(2)) // '0'

结果为0?我在右移后寻找的预期输出是:

111111111100000000000000000000000000000011 // pre
001111111111000000000000000000000000000000 // post >> 

这是如何实现的?

Javascript 数字的按位运算符“如同”对 32 位整数起作用。

>>(数字的符号传播右移)将首先 convert to a 32-bit integer。如果您阅读链接规范,请特别注意

Let int32bit be int modulo 232.

换句话说,所有高于 32 的位都将被忽略。对于您的号码,结果如下:

111111111100000000000000000000000000000011
┗removed━┛┗━━━━━━━━━━━━━━32bit━━━━━━━━━━━━━┛

如果需要,可以使用BigInt:

const n = 4393751543811n; // note the n-suffix
console.log(n.toString(2))
console.log(n & 0b11n) // for BigInt, all operands must be BigInt
const m = n >> 2n;
// The expected.
console.log(m.toString(2))

spec for >> on BigInt 使用了 BigInt::leftShift(x, -y),其中又声明:

Semantics here should be equivalent to a bitwise shift, treating the BigInt as an infinite length string of binary two's complement digits.