Sunday, 2 June 2013

Using enum as Bit field in C#

Bit field allocates meaning or name to each bit in a word (e.g. 32-bit machine word), and use bitwise operators to check conditions and combinations or them. For example, if you have 4-bit word (i.e. each memory address stores a 4-bit value), you could have;

option 1 = 0001
option 2 = 0010
option 3 = 0100

and check which option has been selected by checking which bit out of four has been set to 1.
In this case, 0111 will indicate that all of the options has been chosen, and 0011 would mean option 1 and 2.


In C#, you can indicate an enum as a bit field by using [Flags] attribute as follows;


In this example, the bits indicate whether certain sections are showing on a window. By using bitwise operators, you can check conditions. Applying bitwise-OR (|) to enum values mean that all of the mentioned values are included, and testing whether the result of bitwise-AND (&) with desired value is 0 can tell if the particular bit is set.

'setting' value above has both Panel1 and Panel2 flags set to 1, so checking if the setting includes Panel1 would be true. This is because 'setting' would have value 0001 | 0010, which is equal to 0011, and 0011 & 0001 is equal to 0001 (as bitwise-AND operator leaves only the 1s that occur in both right-hand side and left-hand side of the equation). 0001 is not equal to 0, so the if-case would be evaluated to true.


No comments:

Post a Comment