V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
rabbbit
V2EX  ›  问与答

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

  •  
  •   rabbbit · 2018-07-01 20:05:20 +08:00 · 1421 次点击
    这是一个创建于 2117 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Python

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

    JavaScript

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

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

    geelaw
        1
    geelaw  
       2018-07-01 20:14:37 +08:00   ❤️ 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  
       2018-07-01 20:15:57 +08:00
    应该是 python 为什么不是负数吧
    MiffyLiye
        4
    MiffyLiye  
       2018-07-01 20:22:01 +08:00   ❤️ 1
    而 Python 里整数是无限长的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3347 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 12:01 · PVG 20:01 · LAX 05:01 · JFK 08:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.