位掩码和 javascript 的问题
我不确定我是否做错了什么,但我似乎无法让这个简单的 javascript 工作:
var a = 0;
a |= (1 << 31);
alert(a);
a |= (1 << 30);
alert(a);
你可以在这里看到它 http://jsfiddle.net/qPEVk/
不应该是3221225472吗?
谢谢,
乔
I am not sure if I am doing something wrong, but I can't seem to have this simple javascript to work:
var a = 0;
a |= (1 << 31);
alert(a);
a |= (1 << 30);
alert(a);
you can see it here
http://jsfiddle.net/qPEVk/
shoudln't it 3221225472 ?
thanks,
Joe
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从技术上讲,这没有任何问题,并且预计会出现负数,因为它正在转换为 32 位有符号 int。
基本上,前导位表示“负数或正数”,因此当您翻转它(使用
1<<31
)时,您会得到一个负数。您的位掩码仍然可以像您期望的那样在最多 32 位上工作。 JavaScript 中的位掩码不能超过 32 位。
There is technically nothing wrong with that, and a negative number is expected because it's casting to a 32bit signed int.
Basically, the leading bit means "negative or positive", so when you flip it (with
1<<31
) you get a negative number.Your bitmask will still work exactly like you expect on up to 32 bits. You can't exceed a 32-bit bitmask in JavaScript.
在上面的例子中,b 最终会是 -3221225472。
In the above case, b will end up as -3221225472.