mammadalius
mammadalius

Reputation: 3353

How to read a single BIT in an Array of Bytes?

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

Answers (3)

Tank
Tank

Reputation:

    private bool BitCheck(byte b, int pos)
    {
        return (b & (1 << (pos-1))) > 0;
    }

Upvotes: 2

Spencer Ruport
Spencer Ruport

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

Henk Holterman
Henk Holterman

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

Related Questions