代码之家  ›  专栏  ›  技术社区  ›  Terry5

为什么呢。lshift(1,40)是256,而不是109951162776

  •  0
  • Terry5  · 技术社区  · 2 年前

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

    卢阿

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

    python

    1 << 40   --> 1099511627776
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Luatic    2 年前

    那是因为 bit.lshift 使用32位(假设这是 bitop 在PUC Lua 5.1/LuaJIT下运行的图书馆:

    最好定义在所有平台上都能使用相同的语义。这说明所有操作都基于32位整数的公分母。( https://bitop.luajit.org/semantics.html#range )

    所以它在 2^32 这样就产生了结果 2^(40-32) = 2^8 = 256 .

    而Python使用的是bigint:

    $ 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