Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I tried left-shift in python and lua, but get different result

lua

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

python

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1 << 40   --> 1099511627776

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading