Clever Use of binary authentication permissions, clever use of binary Permissions
Source: http://zxlovenet.cnblogs.com
There are multiple permission levels in the permission assignment, and different users have multiple different permissions.
Forum permissions:
View, post, vote, search
User Permissions:
User A: View and post
User B: View
User C: View, post, vote, search
Analysis:
There are four different permission levels, a total of 2 ^ 4 permission allocation methods.
In this way, permission levels are the best choice for users with different levels. That is, each operation permission is represented by a binary number (1, 10, 100, 1000 ). A total of 2 ^ n permission types are available. n indicates the permission category. In C #, the long type has 64 bits, so there are 64 class permissions in total, and 2 ^ 64 permission allocation methods. Permissions are allocated, deleted, and viewed in binary format.
Long userrolevalue; // user's operation permission
Long oprolevalue; // operation permission
1. Permission allocation (or operation)
Userrolevalue = userrolevalue | oprolevalue
(00001110) 2 = (00000010) 2 | (00000100) 2 | (00001000) 2
2. delete permissions (seeking for compensation and calculation)
Userrolevalue = userrolevalue &(~ Oprolevalue)
3. Permission verification (and calculation)
(Userrolevalue & oprolevalue) = oprolevalue
(00000101) 2 & (00000011) 2 = (00000001) 2
If the verification is successful, you have permissions of the corresponding category.
This verification method can also be used for menu permission verification. You can select a data type based on the number of permission levels to be divided. For example, the default value of the int type is 32 bits, and the short value is 16 bits.
Appendix: the logical (Boolean) operator is used to calculate the expression of the bool result. The result of the operation is bool. The calculation result is as follows:
| Operator |
Operation |
Example |
Result |
| & |
AND (AND) |
False & true |
FALSE |
| | |
OR (OR) |
False | true |
TRUE |
| ^ |
XOR (exclusive or) |
False ^ true |
TRUE |
| ! |
NOT (NOT) |
! False |
TRUE |
| && |
AND (Short Circuit) |
False & true |
FALSE |
| | |
OR (Short Circuit) |
False | true |
TRUE |