Javascript 位运算符在2^31之后停止工作

Javascript 位运算符在2^31之后停止工作,javascript,architecture,bitwise-operators,bitwise-and,bitwise-or,Javascript,Architecture,Bitwise Operators,Bitwise And,Bitwise Or,假设我有这个: // 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

假设我有这个:

// 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件事情并不是什么大不了的事,但有时我需要更多。有没有办法绕过这个限制?按位运算符是如此快速和方便。

正如您所怀疑的,这显然是javascript中整数的宽度问题。根据,js中的数字可以增加到2^53,因此可以有53个不同的位。据介绍,在64位机器中,php一直到2^63-1,因此得到62位。

如果您需要更多,您应该重新考虑您的设计-您是否可以将这些标志分为2个(或更多)组,每个组都有自己的含义(如与食物相关的动作、其他动作、任何其他动作等)?

您可以在中阅读更多关于它的信息,ECMAScript是JavaScript的子集,请检查和


语言?您会说,“PHP…也是。”很抱歉,上面的示例是JavaScript。
` 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. `