Reputation: 3353
The problem is that I have an Array of Byte with 200 Indexes and just want to check that is the Fourth bit of MyArray[75] is Zero(0) or One(1).
byte[] MyArray; //with 200 elements
//check the fourth BIT of MyArray[75]
Upvotes: 3
Views: 2288
Reputation:
private bool BitCheck(byte b, int pos)
{
return (b & (1 << (pos-1))) > 0;
}
Upvotes: 2
Reputation: 35117
The fourth bit in element 75?
if((MyArray[75] & 8) > 0) // bit is on
else // bit is off
The & operator allows you to use a value as a mask.
xxxxxxxx = ?
00001000 = 8 &
----------------
0000?000 = 0 | 8
You can use this method to gather any of the bit values using the same technique.
1 = 00000001
2 = 00000010
4 = 00000100
8 = 00001000
16 = 00010000
32 = 00100000
64 = 01000000
128 = 10000000
Upvotes: 8
Reputation: 273784
Something like:
if ( (MyArray[75] & (1 << 3)) != 0)
{
// it was a 1
}
Assuming you meant 4th bit from the right.
And you might want to check out System.Collections.BitArray
, just to be sure you're not reinventing the wheel.
Upvotes: 4