Define and use bit masks in C#

[bit masks]

The example Understand bit masks in C# explains how to use bit masks. To define a bit mask, simply create an enum and give it the Flags attribute as in the following code.

private enum BitmaskEnum
    Value1 = 1,
    Value2 = 2,
    Value3 = 4,
    Value4 = 8,
    Value5 = 16,

If you do not specify numeric values for the enumerated names, the enum gives them the values 1, 2, 3, and so forth. If you want all of the names to represent distinct values, you should set them equal to different powers of 2 as in the preceding code. Then you can combine them in any combination by using bitwise operators.

The enumeration can also define combined values if you like. For example, you could use the following code to create a value that includes both Value3 and Value5.

    Value3and5 = Value3 | Value5,

The enum doesn’t automatically make the values be powers of two, so what do you get by using the Flags attribute? The attribute tells code designers and other programs that enumerations marked with the attribute are intended to be bit masks. Even more directly useful is the fact that it allows the enum to handle combined values when you invoke its ToString method. For example, consider the following code.

NormalEnum normal_value = NormalEnum.Value1 | NormalEnum.Value2;
BitmaskEnum bitmask_value = BitmaskEnum.Value1 | BitmaskEnum.Value2;

Each of these statements makes a value that combines two other values. The code’s definition of NormalEnum is the same as the definition of BitmaskEnum except it doesn’t use the Flags attribute. Both of the combined values are 1 | 2 = 0001 | 0010 = 0011 = 3.

When you display invoke the values’ ToString methods, however, C# knows that bitmask_value is a flag type so it displays its value accordingly. The following text shows how the program displays the two values.

normal_enum = 3
bitmask_enum = Value1, Value2

The example program displays various values in its TextBox when it starts. For example, the following code shows how the program displays the value of NormalEnum.Value1.

txtValues.Text =
    NormalEnum.Value1 + " = " + (int)NormalEnum.Value1 + "\r\n" +

First this statement displays the value itself. The program automatically converts it into text, so the result is the name of the enumerated value. The code then adds the value converted into an integer, followed by a new line. The code displays the other values similarly.

Download the example program to see how it handles the other values in the two bit masks that it defines.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in algorithms, calculations, mathematics, variables and tagged , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *