Pregunta

Say I have this:

// 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 */

Then if I run it, it will print out that I can eat, sleep and play. It will not print out that I can be jesus, because that number is 2^70. If I make the number 2^31 then it will work (I'm on a 64bit machine but must be running Chrome in 32bit mode when I ran the above example).

I face this problem in PHP all the time as well, when dealing with bitwise operators. Often I can work the scenario I'm in to make it so having a maximum of 31 or 63 things in my list isn't a big deal, but sometimes I need to have much more than that. Is there any way around this limitation? Bitwise operators are so speedy, and convenient.

¿Fue útil?

Solución

Well, the problem with this is apparently, as you suspected, the width of the integer in javascript. According to this, numbers in js can go up to 2^53, so you can have 53 different bits. According to this, in 64-bit machines, php goes all the way up to 2^63 - 1, so you get 62 bits.
If you need more, you should re-think your design - could you perhaps divide the flags into 2 (or more) groups, where each group has its own meaning (like food-related actions, other actions, anything else, etc.)?

Otros consejos

You can read more about it in the ECMAScript Language Specification, ECMAScript is a subset of JavaScript, check here and here.

` 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. `
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top