【发布时间】:2018-01-30 05:37:07
【问题描述】:
我正在尝试在 JS 中创建一个 32 位位掩码。但是,我不明白这里发生了什么:
$ node
> const num = Math.pow(2, 31) - 1
undefined
> num
2147483647
# So far, so good
> num.toString(2)
'1111111111111111111111111111111'
> num.toString(2).length
31
# According to MDN, the left-shift operator does:
# "Excess bits shifted off to the left are discarded.
# Zero bits are shifted in from the right."
# But that's not what we see here. Instead, it seems to be wrapping.
> num << 1
-2
> (num << 1).toString(2)
'-10'
根据我对the MDN docs 的理解,我希望位掩码为31 个1s,后跟1 个0。相反,我得到-10。这是怎么回事?
【问题讨论】:
标签: javascript bit-manipulation