英文:
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 << 7 | 144366253 >> 32 - 7) + 4023233417
Javascript:
var x = (144366253 << 7) | (144366253 >> (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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论