05 May 2011

C# - Bitwise flags (bitmask)

Bitwise flags allow you to combine multiple flags into a single integer.
This really applies to many programming languages.
In C# you can do it like this:

The flags

The following defines the flags.
Notice how the value doubles - are powers of two - for each flag (binary system).
The flags attribute  indicates that bitwise operators will be performed on this enum.
[Flags]
public enum Role{
  AuxCreator = 1,
  AuxEditor  = 2,
  AuxDeletor = 4
}

Combine them

Getting the integer that combines some flags is easy using the bitwise or operator:
int roles = Role.AuxCreator | Role.AuxDeletor; //roles = 5

Check for flag set

Then, you can check whether a certain flag is set in the integer using the bitwise and operator as follows:
bool isAuxDeletor = (roles & Role.AuxDeletor) == Role.AuxDeletor; //isAuxDeletor = true

Unset a flag

To unset a flag from the bitmask, you can use the bitwise and operator again, with the inverse of the flag:
int roles = Role.AuxCreator & (~Role.AuxDeletor); //roles = 1

No comments:

Post a Comment