C# 我如何检查位掩码是否包含位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14479981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:58:19  来源:igfitidea点击:

How do I check, if bitmask contains bit?

c#bit-manipulationbitmask

提问by Nicolai

I don't quite understand this whole bitmask concept.

我不太明白整个位掩码的概念。

Let's say I have a mask:

假设我有一个面具:

var bitMask = 8 | 524288;

I undestand that this is how I would combine 8and 524288, and get 524296.

我不明白这就是我如何组合8and524288和 get 的方式524296

BUT, how do I go the other way? How do I check my bitmask, to see if it contains 8and/or 524288?

但是,我怎么走另一条路?我如何检查我的位掩码,看看它是否包含8和/或524288

To make it a bit more complex, let's say the bitmask I have is 18358536and I need to check if 8and 524288are in that bitmask. How on earth would I do that?

为了让它更复杂一点,假设我拥有的位掩码是18358536,我需要检查8524288是否在该位掩码中。我到底要怎么做?

采纳答案by tschmit007

well

if (8 & bitmask == 8 ) {
}

will check if the bitmask contains 8.

将检查位掩码是否包含 8。

more complex

更复杂

int mask = 8 | 12345;
if (mask & bitmask == mask) {
   //true if, and only if, bitmask contains 8 | 12345
}

if (mask & bitmask != 0) {
   //true if bitmask contains 8 or 12345 or (8 | 12345)
}

may be interested by enum and more particularly FlagsAttibute.

可能对 enum 感兴趣,尤其是FlagsAttibute

回答by Alex

I'm pretty sure (A & B)==Bwhere Ais the bitmask and Bis whatever you want to check should do.

我很确定位掩码(A & B)==B在哪里A,以及B您想检查的任何内容。

Example:

例子:

if((18358536 & 8) == 8) 
{
    // mask contains 8
}

回答by Astrus

First of all, bitmasks are for operating on bits, not integers. It is much easier to understand when we deal with just 1's and 0's than more complex numbers.

首先,位掩码用于操作位,而不是整数。当我们只处理 1 和 0 时,比处理更复杂的数字更容易理解。

So for example:

例如:

1000110000010000100001000 = 18358536 // in binary.

0000010000000000000000000 = 524288   // in binary.

0000000000000000000001000 = 8        // in binary.

0000010000000000000001000 = 524296   // in binary.

With this, it is clear that integer 8 is a 4th bit from the right side and no other bits marked, so when we add 8 to 524288 (20th bit only) we are simply marking 4th and 20th bits as being true. So we can use the same space in memory reserved for an integer to hold multiple flags that define some boolean properties.

有了这个,很明显整数 8 是从右侧开始的第 4 位并且没有标记其他位,因此当我们将 8 添加到 524288(仅第 20 位)时,我们只是将第 4 位和第 20 位标记为真。因此,我们可以使用为整数保留的相同内存空间来保存定义一些布尔属性的多个标志。

As Alex already explained, you can then check if any flag is available in bitmask by using bitwise AND operator:

正如亚历克斯已经解释的那样,您可以使用按位 AND 运算符检查位掩码中是否有任何标志可用:

if ((mask & flag) == flag) { /* mask has flag set as true */ }

You can read everything about bitmasks in this article

您可以在本文中阅读有关位掩码的所有内容