如何使用 AND 检查 C# 中是否存在某个位?
如何使用逻辑运算符来确定是否已设置位,或者位移是唯一的方法?
我发现这个使用位移位的问题,但是我想我可以AND
得出我的价值。
对于某些上下文,我正在从 Active Directory 读取一个值并尝试确定它是否是架构基础对象。我认为我的问题是语法问题,但我不知道如何纠正它。
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
}
}
}
当我查看调试器时: resFlag
是一个object{int}
,值为0x00000010
。 isFlag_Schema_Base_Object
,是0x02
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.
For some context, I'm reading a value from Active Directory and trying to determine if it a Schema Base Object. 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
.isFlag_Schema_Base_Object
, is 0x02
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您知道要检查哪个位并且正在处理 int,则可以使用 BitVector32。
使用位移位可能比使用 CreateMask 更干净。但它就在那里:)
If you know which bit to check and you're dealing with int's you can use BitVector32.
Using bitshifting is probably cleaner than using CreateMask. But it's there :)
resFlag
为0x00000010
,十进制为 16,二进制为10000
。因此,您似乎想测试位 4(位 0 是最低有效位),尽管您的评论说“如果设置了位 10”。如果您确实需要测试位 4,则需要将
isFlag_Schema_Base_Object
初始化为 16,即0x10
。不管怎样,你是对的 - 你不需要进行位移来查看是否设置了一个位,你可以将值与仅设置了该位的常量进行
AND
,然后查看结果是否是非零的。如果该位已设置:
但如果该位未设置:
话虽如此,使用值
1<<4
初始化isFlag_Schema_Base_Object
可能会更清楚,明确您正在测试位 4 是否已设置。resFlag
is0x00000010
which is 16 in decimal, or10000
in binary. 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".If you do need to test bit 4, then
isFlag_Schema_Base_Object
needs to be initialised to 16, which is0x10
.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.If the bit is set:
But if the bit isn't set:
Having said that, it might be clearer to initialise
isFlag_Schema_Base_Object
using the value1<<4
, to make it clear that you're testing whether bit 4 is set.