JavaScript 中的位移
我有一个非常大的数字:5799218898。并且想将其右移到 13 位。
所以,windows-calculator 或 python 给了我:
5799218898 >> 13 | 100010100100001110011111100001 >> 13 70791 | 10001010010000111
正如预期的那样。
但是 Javascript:
5799218898 >> 13 | 100010100100001110011111100001 >> 13 183624 | 101100110101001000
我认为这是因为 javascript 中的内部整数表示,但找不到任何相关信息。
I've got a really big number: 5799218898. And want to shift it right to 13 bits.
So, windows-calculator or python gives me:
5799218898 >> 13 | 100010100100001110011111100001 >> 13 70791 | 10001010010000111
As expected.
But Javascript:
5799218898 >> 13 | 100010100100001110011111100001 >> 13 183624 | 101100110101001000
I think it because of internal integer representation in javascript, but cannot find anything about that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 ECMAScript (Javascript) 中,按位运算始终为 32 位。因此 5799218898 被切成 32 位,变成 1504251602。这个整数 >>> 13 给出 183624。
在 Python 中,它们是任意长度的整数。所以没有问题。
(Windows计算器中的数字是64位的,足以容纳5799218898。)
(正确答案应该是707912。)
In ECMAScript (Javascript) bitwise operations are always in 32-bit. Therefore 5799218898 is chopped into 32-bit which becomes 1504251602. This integer >> 13 gives 183624.
In Python they are arbitrary-length integers. So there's no problem.
(And the numbers in Windows calculator are 64-bit, enough to fit 5799218898.)
(And the correct answer should be 707912.)
如果您使用现代浏览器,则可能需要对大于 32 位有符号的值使用 bigint。它们早在 2020 年就在 ECMAScript 语言第 11 版中引入。
据称,您还可以找到一个浏览器兼容性表:
您可以执行以下操作,例如在 Chrome 中进行测试:
If you have a modern browser, you might want to use bigint for values greater than 32-bit signed. They were introduced in the 11-th Edition of ECMAScript Language back in 2020.
It is stated, you also find a browser compatibility table:
You can do the following, tested for example in Chrome:
正如 Nicholas Zakas 所述:
As Nicholas Zakas states:
您拥有的数字 (5799218898) 超出了 32 位。您没有提到您正在测试的 JavaScript 引擎,但它很可能是 32 位的。
要进行测试,请修剪数字开头的“5”,以便落在 32 位边界内。那么你的轮班应该可以正常进行。
The number you have (5799218898) is beyond 32 bits. You didn't mention the JavaScript engine you're testing with, but it's very likely that it is 32-bit.
To test, trim the "5" at the beginning of your number so that you fall inside the 32-bit boundary. Then your shift should work fine.