using a byte as a bit mask.

  • Thread starter Thread starter bob
  • Start date Start date
B

bob

Hi,
Having trouble determining if bit n in a byte is on or off.
Seem to remember being able to do this with the logical And operator
something like if (2 & mybyte) { do something}
Maybe I am dreaming of VB days.
Is there a succint way of doing this?
thanks
Bob
 
Hi Bob

You are on the right track, try something like this
if ((bits & 1) != 0) // bit is set if not zero

where bits is an byte, uint or ulong.
Exhange 1 for the bit you would like to check, i.e. 1,2,4,8,16,32, ....
 
Hi,
Having trouble determining if bit n in a byte is on or off.
Seem to remember being able to do this with the logical And operator
something like if (2 & mybyte) { do something}
Maybe I am dreaming of VB days.
Is there a succint way of doing this?
thanks
Bob

It's similar here , you use & or | , note that it's only one if you
use two (&&) it's the logic operation instead of the bit operation.
 
public bool IsBitSet(byte value, byte bitNumber)
{
return value & (1 << bitNumber);
}

Something like that anyway :-)
 
Peter said:
public bool IsBitSet(byte value, byte bitNumber)
{
return value & (1 << bitNumber);
}

Something like that anyway :-)

Close. ;)

return (value & (1 << bitNumber)) != 0;

Note, just to be overly clear: bitNumber is zero based.
 
Effectively you just want to check a given value against x..

int value = X; //user input, or saved value
int check = 1<<3; //third to last bit 0x0...001000
bool hasCheck = (value & check == check);


I am pretty sure you can do something like the following...
[Flags]
public enum MyOptions : int {
None= 0,
First= 1,
Second= 1<<1,
Third= 1<<2
}

public bool HasOption(MyOptions value, MyOptions check) {
return (value & check == check);
}
 
Back
Top