How to read one BIT in a byte array?

The problem is that I have an array of bytes with 200 indexes and just want to check if the fourth bit of MyArray [75] is zero (0) or one (1).

byte[] MyArray; //with 200 elements

//check the fourth BIT of  MyArray[75]
+3
source share
3 answers

The fourth bit in element 75?

if((MyArray[75] & 8) > 0) // bit is on
else // bit is off

The operator and allows you to use the value as a mask.

xxxxxxxx = ?
00001000 = 8 &
----------------
0000?000 = 0 | 8

This method can be used to collect 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
+8
source

Sort of:

if ( (MyArray[75] & (1 << 3)) != 0)
{
   // it was a 1
}

Assuming you meant the 4th bit on the right.

And you can check System.Collections.BitArrayto make sure that you are not reinventing the wheel.

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

Source: https://habr.com/ru/post/1714802/


All Articles