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
resFlagis0x00000010which is 16 in decimal, or10000in 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_Objectneeds 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
ANDthe 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_Objectusing the value1<<4, to make it clear that you’re testing whether bit 4 is set.