为什么lua bit.lshift(1,40)是256,而不是109951162776
我尝试了Python和Lua的左移,但是获得了不同的结果
Lua
print(bit.lshift(1, 40)) --> 256
Python
1 << 40 --> 1099511627776
I tried left-shift in python and lua, but get different result
lua
print(bit.lshift(1, 40)) --> 256
python
1 << 40 --> 1099511627776
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为
bit.lshift
使用32位(假设这是bitop
库在Puc Lua 5.1/luajit下运行的库):)它在
2^32
上缠绕,因此使结果2^(40-32)= 2^8 = 256
。python使用bigints :(
这些数字超过64位ints)
在5.3以来具有64位签名整数类型以来的LUA版本,您将获得相同的结果:
5.1中的解决方法:仅在5.1中:简单地乘以
2^^ 40
而不是转移:That's because
bit.lshift
uses 32 bits (assuming this is thebitop
library running under PUC Lua 5.1 / LuaJIT):so it wraps around at
2^32
thus making the result2^(40-32) = 2^8 = 256
.whereas Python uses bigints:
(these numbers well exceed 64-bit ints)
In Lua versions since 5.3, which have a 64 bit signed integer type, you'll get the same result:
workaround in 5.1: Simply multiply by
2^40
instead of shifting: