Information Technology Reference
In-Depth Information
Bit Flags
Programmers have long used the different bits in a single word as a compact way to represent
a set of on/off flags for options. Enums offer a convenient way to implement this.
The general steps are the following:
1.
Determine how many bit flags you need, and choose an unsigned integral type with
enough bits to hold them.
2.
Determine what each bit represents, and declare an enum of the chosen integral type,
with members representing each bit.
3.
Use the bitwise OR operator to set the appropriate bits in a word holding the bit flags.
4.
Unpack the bit flags by using the bitwise AND operator.
For example, the following code shows the enum declaration representing the options for
a card deck in a card game. The underlying type, uint , is more than sufficient to hold the four
bit flags needed. Notice the following about the code:
￿
The members have names that represent the options and are set to the value represent-
ing the value of a particular bit.
Decorating the enum with the Flags attribute is not actually necessary, but gives some
additional convenience, which I will discuss shortly.
￿
[Flags]
enum CardDeckSettings : uint
{
SingleDeck = 0x01, // Bit 0
LargePictures = 0x02, // Bit 1
FancyNumbers = 0x04, // Bit 2
Animation = 0x08 // Bit 3
}
Note Hexadecimal representation is often used when working with bits because there is a more direct cor-
relation between the hex representation of a number and its bit pattern than with the decimal representation.
Search WWH ::




Custom Search