C# extension - enumeration | bit calculation, quickly combine options

Disclaimer: This article is a personal note, used for study and research, non-commercial use, the content is obtained from personal research and comprehensive collation, if there is any violation, please contact, and the violation must be corrected.


C# extension - enumeration | bit calculation, quickly combine options



1. Development environment

Language: C#


2. Problem description

When multiple enumeration values ​​are filtered and combined, how to use | quick combination. For example, five colors want to combine three of them into one option for filtering.


3. Solution principle and code

Realization principle:

In the following code, the five constants Red, Green, Blue, Yellow, and Black are combined using the | operator to form a flag color, indicating the color to be filtered. (Simple understanding is that colors contains five color options)
When filtering, use the & operator to perform a bitwise AND operation on the color of the item and colors. If the result is not 0, it means that the color of the item is included in colors and meets the filtering conditions . (Binary comparison. Use the bitwise AND (&) operator to compare whether the result is 0. The bitwise AND (&) operator is to perform "AND" operation on the corresponding binary bits of two integer numbers:)

Corresponding code:

Example 1:


enum Color
{
    
    
    Red = 1,
    Green = 2,
    Blue = 4,
    Yellow = 8,
    Black = 16
}

List<Item> items = GetItemList(); // 获取物品列表

// 筛选出颜色为 Red、Green、Blue、Yellow 或 Black 的物品
Color colors = Color.Red | Color.Green | Color.Blue | Color.Yellow | Color.Black;
List<Item> filteredItems = items.Where(i => (i.Color & colors) != 0).ToList();

Example 2:
Suppose there are three colors corresponding to binary values:

Color colors = Color.Red | Color.Green | Color.Blue; // 需要筛选的三种颜色为 Red、Green、Blue
List<Item> filteredItems = items.Where(i => (i.Color & colors) != 0).ToList(); // 筛选颜色包含在 colors 中的物品

principle:

Red: 0001
Green: 0010
Blue: 0100
然后将这三个值用 | 运算符组合起来,得到一个标志位 colors,其二进制值为:

colors: 0111
然后,假设有一个物品,它的颜色对应的二进制值为:

ItemColor: 0010
然后将 ItemColor 与 colors 进行按位与(&)运算:

ItemColor & colors: 0010 & 0111 = 0010
通过按位与(&)运算得到的结果是一个整型数,其二进制值为 0010,这意味着第二位(对应 Green 颜色)是 1,而其他位都是 0。这表示该物品的颜色包含 Green,符合筛选条件。如果按位与的结果为0,则说明该物品的颜色不包含在筛选条件中。

Note:
In an enumerated type, the value of each constant must be a power of 2, so as to ensure that only one bit in the binary representation of each constant is 1. This allows multiple constants to be combined into one flag using the | operator. In the above code, constant values ​​of 1, 2, 4, 8, and 16 are used for convenience, and they are all powers of 2.

Four. Summary

Stay hungry, stay stupid.
The only thing the world can trust is your hard work and your journey.

Guess you like

Origin blog.csdn.net/weixin_45532761/article/details/130938721