[英]How do I check for presence of a bit in C# using AND?
How to I use logical operators to determine if a bit is set, or is bit-shifting the only way? 如何使用逻辑运算符确定是否设置了位,或者移位是唯一方法?
I found this question that uses bit shifting, but I would think I can just AND
out my value. 我发现这个问题 ,使用位移,但我认为我可以AND
我的价值。
For some context, I'm reading a value from Active Directory and trying to determine if it a Schema Base Object. 对于某些情况,我正在从Active Directory中读取一个值,并尝试确定它是否为架构基础对象。 I think my problem is a syntax issue, but I'm not sure how to correct it. 我认为我的问题是语法问题,但是我不确定如何更正它。
foreach (DirectoryEntry schemaObjectToTest in objSchema.Children)
{
var resFlag = schemaObjectToTest.Properties["systemFlags"].Value;
//if bit 10 is set then can't be made confidential.
if (resFlag != null)
{
byte original = Convert.ToByte( resFlag );
byte isFlag_Schema_Base_Object = Convert.ToByte( 2);
var result = original & isFlag_Schema_Base_Object;
if ((result) > 0)
{
//A non zero result indicates that the bit was found
}
}
}
When I look at the debugger: resFlag
is an object{int}
and the value is 0x00000010
. 当我查看调试器时: resFlag
是一个object{int}
,值是0x00000010
。 isFlag_Schema_Base_Object
, is 0x02
isFlag_Schema_Base_Object
,是0x02
resFlag
is 0x00000010
which is 16 in decimal, or 10000
in binary. resFlag
是0x00000010
,十进制为16,二进制为10000
。 So it seems like you want to test bit 4 (with bit 0 being the least significant bit), despite your comment saying "if bit 10 is set". 因此,尽管您的注释说“如果设置了第10位”,您似乎还是想测试第4位(第0位是最低有效位)。
If you do need to test bit 4, then isFlag_Schema_Base_Object
needs to be initialised to 16, which is 0x10
. 如果确实需要测试位4,则需要将isFlag_Schema_Base_Object
初始化为16,即0x10
。
Anyway, you are right - you don't need to do bit shifting to see if a bit is set, you can AND
the value with a constant that has just that bit set, and see if the result is non-zero. 无论如何,你是对的-你不需要做比特移位,看是否有位被设置,你可以AND
使用具有只是位设置一个恒定值,看看结果是非零。
If the bit is set: 如果该位置1:
original xxx1xxxx
AND
isFlag_Schema_Base_Object 00010000
-----------------------------------
= 00010000 (non-zero)
But if the bit isn't set: 但是,如果未设置位:
original xxx0xxxx
AND
isFlag_Schema_Base_Object 00010000
-----------------------------------
= 00000000 (zero)
Having said that, it might be clearer to initialise isFlag_Schema_Base_Object
using the value 1<<4
, to make it clear that you're testing whether bit 4 is set. 话虽如此,使用值1<<4
初始化isFlag_Schema_Base_Object
可能更清楚,以明确表明您正在测试是否设置了位4。
If you know which bit to check and you're dealing with int's you can use BitVector32 . 如果您知道要检查的位并且正在处理int,则可以使用BitVector32 。
int yourValue = 5;
BitVector32 bv = new BitVector32(yourValue);
int bitPositionToCheck = 3;
int mask = Enumerable.Range(0, bitPositionToCheck).Select(BitVector32.CreateMask).Last();
bool isSet = bv[mask];
Using bitshifting is probably cleaner than using CreateMask. 使用移位比使用CreateMask可能更干净。 But it's there :) 但它在那里:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.