) C # Use bitwise operations to manage permissions

Source: Internet
Author: User

Common bitwise operations include (&), (|), and (~), For example:

1 & 0 = 0, 1 | 0 = 1 ,~ 1 = 0

When designing the permission, we can convert the permission operation into bitwise operations for processing.

Step 1: Create an enumeration to indicate all permission operations:

 
[Flags]
 
Public EnumPermissions
 
{
 
Insert = 1,
 
Delete = 2,
 
Update = 4,
 
Query = 8
 
}
 
 

[Flags] indicates that this enumeration can support bitwise operations. For each enumerated value, we use the Npower of 2 to assign a value. In this way, the value is 1 = 0001 in binary format, 2 = 0010, 4 = 0100, 8 = 1000, etc. Each digit indicates a permission. 1 indicates that the permission is granted, and 0 indicates that no.

Next is the permission calculation:

1.Permission AdditionWe know that 0001 | 0100 = 0101, which means that both the First and Third BITs have the permissions, and the enumerated values are:

 
Permissions per = permissions. Insert | permissions. Update

2.Permission Subtraction, And is implemented using operations + non-operations. If you want to remove the insert permission above, the operation is:

 
Permissions per & = ~ Permissions. insert

That is, 0101 &~ 0001 = 0101 & 1110 = 0100

3.Permission judgmentWhen determining whether a user has the operation permission, the user's permission and operation permission should be performed and calculated. If the result is still the operation permission, indicates that the user has this permission:

Permissions per = permissions. Insert | permissions. update;If(Per & permissions. Insert = permissions. insert ){// Operation permission}
 
When the comparison process is 0101 & 0001 = 0001,000, the 0 bits of 1 are set to 0 and the other bits are compared to the 1 bits.
 
 
 
From: http://www.cnblogs.com/xiaosonl/archive/2009/06/17/1505312.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.