gpt4 book ai didi

javascript - 与左移运算符混淆

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:41:00 26 4
gpt4 key购买 nike

我正在尝试在 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 个 1 后跟 1 个 0 的位掩码。相反,我得到 -10。这是怎么回事?

最佳答案

Javascript 没有Integer,但位运算符只对Integer 有意义。

因此在按位运算符之前,javascript 会将 ToInt32(val) 应用于您的数字。

对于“有符号 32 位整数”,最高位表示“有符号”。

最后,您的数字溢出了“有符号位”。

我的英文不好,你可以看看ECMAScript的Language Specification。

关于javascript - 与左移运算符混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48514551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com