How do I compare multiple bits of data?

Question:

There is a data byte in bin: 11010000, how can you check that the first 3 bits are 110?

Answer:

One of many ways:

(bin >> 5) & 7 == 6

What's happening:

  1. Shift the desired bits to the left

     xxxxxxxx11010000 // было xxxxxxxxxxxxx110 // стало
  2. Apply a mask that will pull out only the bits you need:

     xxxxxxxxxxxxx110 // было 111 // маска 0000000000000110 // стало
  3. The result is compared with the desired combination of bits (binary 110 is 6).


Usually you shouldn't want to compare bits manually, this is too low-level operation. Bitfields are often better suited for things like this:

struct Data
{
    unsigned int p1 : 3; // первые три бита
    unsigned int p2 : 1; // следующий 1 бит
    unsigned int p3 : 4; // следующие 4 бита
};

Data data;
// ...
if (data.p1 == 6)
{

Here the compiler will do all the changes for you.

Scroll to Top