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

why lua bit.lshift(1, 40) is 256, not 1099511627776

我在 python 和 lua 中尝试了左移,但得到了不同的结果

lua

print(bit.lshift(1, 40))  --> 256

python

1 << 40   --> 1099511627776

那是因为bit.lshift使用了32位(假设这是PUC Lua 5.1 / LuaJIT下的bitop库运行):

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)

所以它在 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 位整数)

在 5.3 之后的 Lua 版本中,具有 64 位有符号整数类型,您将得到相同的结果:

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

5.1 中的解决方法:只需乘以 2^40 而不是移位:

$ lua5.1
> =2^40
1099511627776