rabbbit
V2EX  ›  问与答

为什么 JavaScript 位运算左移会输出负数?

  •  
  •   rabbbit · Jul 1, 2018 · 1831 views
    This topic created in 2900 days ago, the information mentioned may be changed or developed.

    Python

    3 << 29
    # 1610612736
    3 << 30
    # 3221225472L
    

    JavaScript

    3 << 29
    // 1610612736
    3 << 30
    // -1073741824
    

    为什么 JavaScript 位运算左移会输出负数?

    geelaw
        1
    geelaw  
       Jul 1, 2018   ❤️ 1
    搜索 javascript left shift

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators

    Bitwise operators treat their operands as a sequence of 32 bits (zeroes and ones).

    ...

    Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

    ...

    Signed 32-bit integers

    The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format.
    mooncakejs
        2
    mooncakejs  
       Jul 1, 2018
    应该是 python 为什么不是负数吧
    MiffyLiye
        4
    MiffyLiye  
       Jul 1, 2018   ❤️ 1
    而 Python 里整数是无限长的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5511 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 06:42 · PVG 14:42 · LAX 23:42 · JFK 02:42
    ♥ Do have faith in what you're doing.