为什么lua bit.lshift(1,40)是256,而不是109951162776

发布于 2025-01-27 03:05:29 字数 185 浏览 2 评论 0原文

我尝试了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 技术交流群。

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

发布评论

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

评论(1

回心转意 2025-02-03 03:05:29

这是因为bit.lshift使用32位(假设这是bitop库在Puc Lua 5.1/luajit下运行的库):

希望定义所有平台上相同的语义。这决定所有操作均基于32位整数的共同点。 ( https://bitop.luajit.org/semantics.htmlantics.html#range ) /p>

)它在2^32上缠绕,因此使结果2^(40-32)= 2^8 = 256

python使用bigints :(

$ python3
Python 3.8.10 (default, Mar 15 2022, 12:22:08) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 << 128
340282366920938463463374607431768211456
>>> 1 << 256
115792089237316195423570985008687907853269984665640564039457584007913129639936

这些数字超过64位ints)

在5.3以来具有64位签名整数类型以来的LUA版本,您将获得相同的结果:

$ lua
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
> 1 << 40
1099511627776

5.1中的解决方法:仅在5.1中:简单地乘以2^^ 40而不是转移:

$ lua5.1
> =2^40
1099511627776

That's because bit.lshift uses 32 bits (assuming this is the bitop library running under PUC Lua 5.1 / LuaJIT):

It's desirable to define semantics that work the same across all platforms. This dictates that all operations are based on the common denominator of 32 bit integers. (https://bitop.luajit.org/semantics.html#range)

so it wraps around at 2^32 thus making the result 2^(40-32) = 2^8 = 256.

whereas Python uses bigints:

$ python3
Python 3.8.10 (default, Mar 15 2022, 12:22:08) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 << 128
340282366920938463463374607431768211456
>>> 1 << 256
115792089237316195423570985008687907853269984665640564039457584007913129639936

(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:

$ lua
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
> 1 << 40
1099511627776

workaround in 5.1: Simply multiply by 2^40 instead of shifting:

$ lua5.1
> =2^40
1099511627776
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文