【问题标题】:Bitwise operators stop working after 2^31位运算符在 2^31 后停止工作
【发布时间】:2012-04-08 01:06:04
【问题描述】:

说我有这个:

// different things you can do
var CAN_EAT = 1,
    CAN_SLEEP = 2,
    CAN_PLAY = 4,
    CAN_DANCE = 8,
    CAN_SWIM = 16,
    CAN_RUN = 32,
    CAN_JUMP = 64,
    CAN_FLY = 128,
    CAN_KILL = 256,
    CAN_BE_JESUS = Math.pow(2, 70);

// the permissions that I have
var MY_PERMS = CAN_EAT | CAN_SLEEP | CAN_PLAY | CAN_BE_JESUS;

// can I eat?
if(MY_PERMS & CAN_EAT) alert('You can eat!'); /* RUNS */

// can I sleep?
if(MY_PERMS & CAN_SLEEP) alert('You can sleep!'); /* RUNS */

// can I play?
if(MY_PERMS & CAN_PLAY) alert('You can play!'); /* RUNS */

// can I be jesus?
if(MY_PERMS & CAN_BE_JESUS) alert('You can be jesus!'); /* WONT RUN */

然后如果我运行它,它会打印出我可以吃饭、睡觉和玩耍。它不会打印出我可以成为耶稣,因为那个数字是 2^70。如果我将数字设为 2^31,那么它将起作用(我在 64 位机器上,但在运行上述示例时必须在 32 位模式下运行 Chrome)。

在处理位运算符时,我在 PHP 中也一直面临这个问题。通常我可以按照我所处的场景来完成它,所以我的列表中最多有 31 或 63 件事情并不是什么大不了的事,但有时我需要的远不止这些。有没有办法绕过这个限制?按位运算符非常快速和方便。

【问题讨论】:

  • 语言?你说,“PHP...也是。”
  • 抱歉,上面的例子是 JavaScript。

标签: javascript architecture bitwise-operators bitwise-and bitwise-or


【解决方案1】:

好吧,正如您所怀疑的那样,这个问题显然是javascript中整数的宽度。根据this,js 中的数字可以达到 2^53,所以你可以有 53 个不同的位。根据this,在 64 位机器中,php 一直到 2^63 - 1,所以你得到 62 位。
如果您需要更多,您应该重新考虑您的设计 - 您是否可以将标志分成 2 个(或更多)组,每个组都有自己的含义(如与食物相关的动作、其他动作、其他任何东西等) ?

【讨论】:

    【解决方案2】:

    您可以在ECMAScript Language Specification 中阅读有关它的更多信息,ECMAScript 是 JavaScript 的子集,请查看 herehere

    ` Some ECMAScript operators deal only with integers in the range -2^31
    through 2^31 - 1, inclusive, or in the range 0 through 2^32-1, inclusive. 
    These operators accept any value of the Number type but first convert 
    each such value to one of 2^32 integer values. 
    See the descriptions of the ToInt32 and ToUint32 operators in 9.5 and 
    9.6, respectively. `
    

    【讨论】:

      猜你喜欢
      • 2015-06-26
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 2016-09-30
      相关资源
      最近更新 更多