Using bitwise operators in> 32 bit integers

I use bitwise operations to represent many access control flags within a single whole.

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 happens on the PHP side of my project. However, there is one part where Javascript is used to combine multiple access flags using | while maintaining the access level. It works great. I found that after an integer (flag) gets too large (> 32 bits), 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 I don’t need to limit the number of access control flags to 32. Each access control flag is twice the previous control flag, so that each control flag will not interfere with the other control flags.

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

I noticed that adding two of these flags along with simple + , it seems to come out with the same answer as the bitwise or operation, but I am having problems wrapping my head around that, a simple substitution, or there may be problems with by this. Can anyone comment on the validity of this workaround? Example:

 (4294967296 | 262144 | 524288) == (4294967296 + 262144 + 524288) 
+4
source share
2 answers

Just adding flags will work if you know for sure that each flag has a power of two, and that you don't go past 52 bits long (due to the sum of a Double-precision float can be saved, since this is what JS uses for numbers) .

If for some reason you need more than 52 flags, I would suggest grouping flags into categories.

+2
source

You cannot have more than 32 if you want to have bitwise operations. To perform bitwise operations, javascript converts a numeric value (which is stored as an 8-byte float) into a 32-bit integer, and then performs bitwise / bit-shift operations on this value. It converts the returned integer back to a floating point before storing in a variable. See the Moz Dev Net Article for more information.

You can still perform integer arithmetic on floats, up to 9007199254740992, which is 2 ^ 53. But you cannot use bitwise operators for 32 bits for the above reason.

Because PHP uses platform-specific integers, you cannot guarantee that PHP can handle more than 32 bits. Therefore, on both sides, I would recommend splitting flags into groups and saving them separately. You can wrap them in objects with accessories to make sure that they behave as one set of flags, not several.

+2
source

Source: https://habr.com/ru/post/1436709/


All Articles