I tried left-shift in python and lua, but get different result
lua
print(bit.lshift(1, 40)) --> 256
python
1 << 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