Javascript位运算在Python中产生不同的结果。

huangapple go评论106阅读模式
英文:

Javascript bitwise operation gives different result in python

问题

我的 JavaScript 代码返回5322244621,但我的 Python 代码返回22502113805。

Python:

x = (144366253 << 7 | 144366253 >> 32 - 7) + 4023233417

Javascript:

var x = (144366253 << 7) | (144366253 >> (32 - 7)) + 4023233417;

我期望 Python 代码返回与 JavaScript 代码相同的结果。

英文:

My javascript code gives 5322244621 but my python code gives me 22502113805

Python:
x = (144366253 &lt;&lt; 7 | 144366253 &gt;&gt; 32 - 7) + 4023233417

Javascript:
var x = (144366253 &lt;&lt; 7) | (144366253 &gt;&gt; (32 - 7)) + 4023233417;

Im expecting the python code to return the same as the javascript code

答案1

得分: 1

第一,你的括号在你的Python和Javascript代码中完全不同。这两个表达式的意义不同,所以预期结果会不同。我无法知道你实际想要哪个版本,但请确保操作顺序匹配。

第二,Javascript中的数字都是浮点数,但按位运算符使用操作数的32位整数版本(请参阅此处)。你的表达式创建了一些超出32位整数范围的相当大的数字,因此会发生溢出。另一方面,Python允许任意大的数字,所以溢出在那里不是问题。

英文:

Two things:

First, your parentheses are completely different your Python and Javascript code. The meaning of the two expressions is different, so it is expected that the result would be different. I don't have any way of knowing which version you actually want, but make sure the order of operations matches.
Second, Javascript numbers are all floating point, but the bitwise operators take a 32 bit integer version of the operands (see here). Your expressions create some pretty large numbers outside the range of a 32 bit integer, so you get overflow. Python, on the other hand, allows arbitrarily large numbers, so overflow isn't an issue there.

huangapple
  • 本文由 发表于 2023年8月10日 23:17:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76877128.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定