Use C# [Flags] enumeration to perform bit operations
Enumerations with the [Flags] attribute allow manipulation of individual bits in the underlying integer representation. This enables succinct representation of bit masks, where each bit represents a specific flag or option.
Set bit
To set a bit in the [Flags] enumeration, use the bitwise OR operator (|):
1 |
|
Test position
To test whether a bit is set, use the bitwise AND operator (&):
1 |
|
Toggle position
To toggle a bit (set if not set, clear if set), use the bitwise XOR operator (^):
1 |
|
Clear bit
To clear bits, use the bitwise AND operator (&) and the complement of the bit mask:
1 |
|
Custom extension method
For convenience, the following extension methods can be defined to simplify these operations:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
These extension methods can be used as follows:
1 2 3 4 5 6 7 8 9 10 11 |
|
The above is the detailed content of How to Perform Bitwise Operations on C# [Flags] Enums?. For more information, please follow other related articles on the PHP Chinese website!