A brief discussion on bit operation permission allocation in C enumeration

  • 2020-05-10 18:41:45
  • OfStack

The commonly used bit operations are and (&), or (|) and not (~), such as:

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

When designing permissions, we can convert the permission management operation to an C# bit operation.

Step 1: establish an enumeration to represent all the permission management operations:


[Flags] 
public enum Permissions 
{ 
Insert = 1, 
Delete = 2, 
Update = 4, 
Query = 8 
} 

[Flags] means that the enumeration can support C# bit operation, and for each value of the enumeration, we use 2 to the n power to assign the value, which is exactly 1 = 0001, 2 = 0010, 4 = 0100, 8 = 1000, etc. Each bit represents a kind of permission, 1 means that it has the permission, and 0 means that it does not.

Next is the operation of permissions:

As we know, 0001 | 0100 = 0101, so it means that the permission management has both the first bit and the third bit, and the enumeration is expressed as:

Permissions per = Permissions.Insert | Permissions.Update

2. The subtraction of permissions is realized by using and operation + non-operation. For example, to remove the Insert permissions above, the operation is as follows:

Permissions per &= ~Permissions.Insert is 0101 & ~0001 = 0101 & 1110 = 0100

3. Judgment, use and operation of permissions. When judging whether user 1 has the operation permissions, the user's permissions and operation permissions should be evaluated and operated.


 Permissions per = Permissions.Insert | Permissions.Update; 
  if(per & PermissionsPermissions.Insert = Permissions.Insert) 
  { 
  // Have access  
  }

The comparison process is 0101 & 0001 = 0001, and the 0 bit of 0001 is used to calculate with C# bit to put all the other bits into 0, so that the 1 bit of only 1 is compared.


Related articles: