Right Shift>>将值转换为零为零、Shift、Right、gt

2023-09-03 11:40:23 作者:挽泪

尝试在Java脚本中进行一些位操作。

考虑以下事项:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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 >> 

如何实现这一点?

推荐答案

数字上的Java位运算符就像32位整数上的位运算符一样工作。

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

设int32bit为整数模232。

换句话说,32以上的所有位都将被忽略。对于您的号码,这将导致以下结果:

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

如果需要,可以使用BigInt

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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),其中依次声明:

此处的语义应等价于按位移位,将BigInt视为二进制二进制补码数字的无限长字符串。