Python/Javascript——整数按位异或问题

发布于 2024-10-08 20:08:17 字数 304 浏览 1 评论 0原文

我精通两种语言...但我在整数位异或逻辑运算符方面遇到问题。在 javascript 中,它给了我一个结果,在 python 中它给了我另一个结果..

继续,打开 python 并执行 (-5270299) ^ 2825379669

现在使用 javascript,进行相同的计算,并警告结果或其他内容(例如 http://thorat.org/OS/js.php)

结果不同!我不知道为什么!

我一定是错过了什么。

I'm proficient with both languages... but I'm having problems with the integer bitwise exclusive or logical operator. In javascript, it gives me one result, in python it gives me another..

Go ahead, open python and execute (-5270299) ^ 2825379669

Now with javascript, do the same calculation, and alert the result or whatever (example at http://thorat.org/OS/js.php)

The results are different! I have no idea why!

I MUST be missing something.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浅听莫相离 2024-10-15 20:08:17

JavaScript 的整数是 32 位,而当值超过 32 位时,Python 会自动转换为无限长度的 long 格式。如果您明确强制 Python 不要对超出 32 位的符号进行扩展,或者将结果截断为 32 位,则结果是相同的:

>>> (-5270299 & 0xFFFFFFFF) ^ 2825379669
1472744368L
>>> (-5270299 ^ 2825379669) & 0xFFFFFFFF
1472744368L

JavaScript's integers are 32-bit whereas Python automatically converts to the unlimited length long format when values exceed 32 bits. If you explicitly force Python not to sign extend past 32 bits, or if you truncate the result to 32 bits, then the results are the same:

>>> (-5270299 & 0xFFFFFFFF) ^ 2825379669
1472744368L
>>> (-5270299 ^ 2825379669) & 0xFFFFFFFF
1472744368L
不可一世的女人 2024-10-15 20:08:17

2825379669 适合 32 位。

JavaScript 中的所有数字都是 64 位浮点数,但是当对它们进行按位运算时,它们会先转换为 32 位整数,然后执行按位运算,然后再转换回 64 位浮点数。

另一方面,Python 很乐意处理整数的长值(超过 32 位)。

因此,如果您希望在 JavaScript 中得到相同的结果,则必须采取一些技巧,例如将 64 位整数存储在两个 JavaScript 数字中,然后对这两个数字进行运算。这将比内置的 float 到 int 和反之转换已经很慢的速度还要慢。

2825379669 does not fit into 32 bits.

All numbers in JavaScript are 64 bit floats, but when doing bitwise operations on them, they get converted to 32 bit integers first, then the bitwise operation is performed, and afterwards they get converted back to a 64 bit float.

Python on the other hand happily handles long values (more than 32 bits) for integers.

So if you want the same result in JavaScript, you'll have to do some tricks, like storing your 64 bit integer in two JavaScript numbers and then do the operations on those two. Which will be even slower than the already horrible slow built in conversion of float to int and back.

毁梦 2024-10-15 20:08:17

不,他们不是。 Python 仅保留符号,因为它可以处理更大的整数。

js> ((-5270299) ^ 2825379669).toString(16)
57c84bb0

>>> hex((-5270299 ^ 2825379669))
'-0xa837b450'
>>> hex((-5270299 ^ 2825379669)+2**32)
'0x57c84bb0'

No they're not. Python merely retains the sign due to the fact that it can handle larger integers.

js> ((-5270299) ^ 2825379669).toString(16)
57c84bb0

>>> hex((-5270299 ^ 2825379669))
'-0xa837b450'
>>> hex((-5270299 ^ 2825379669)+2**32)
'0x57c84bb0'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文