Using bitwise operators on > 32 bit integers

Posted by dqhendricks on Stack Overflow See other posts from Stack Overflow or by dqhendricks
Published on 2012-09-27T22:48:36Z Indexed on 2012/09/28 15:38 UTC
Read the original article Hit count: 327

I am using bitwise operations in order to represent many access control flags within one integer.

ADMIN_ACCESS = 1;
EDIT_ACCOUNT_ACCESS = 2;
EDIT_ORDER_ACCESS = 4;

var myAccess = 3; // ie: ( ADMIN_ACCESS | EDIT_ACCOUNT_ACCESS )

if ( myAccess & EDIT_ACCOUNT_ACCESS ) { // check for correct access
   // allow for editing of account

}

Most of this is occurring on the PHP side of my project. There is one piece however where Javascript is used to join several access flags using | when saving someone's access level. This works fine to a point. I have found that once an integer (flag) gets too large (> 32bit), it no longer works correctly with bitwise operators in Javascript. For instance:

alert( 4294967296 | 1 ); // equals 1, but should equal 4294967297

I am trying to find a workaround for this so that I do not have to limit my number of access control flags to 32. Each access control flag is two times the previous control flag so that each control flag will not interfere with other control flags.

dec(4) = bin(100)
dec(8) = bin(1000)
dec(16) = bin(10000)

I have noticed that when adding two of these flags together with a simple +, it seems to come out with the same answer as a bitwise or operation, but am having trouble wrapping my head around whether this is a simple substitution, or if there might be problems with doing this. Can anyone comment on the validity of this workaround? Example:

(4294967296 | 262144 | 524288) == (4294967296 + 262144 + 524288)

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about math