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

    1 answer 1

    One of many ways:

    (bin >> 5) & 7 == 6 

    What's happening:

    1. Shift the bits to the left

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

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


    Usually you should not want to compare the bits manually, this is too low-level operation. For such pieces, bit fields are often better suited:

     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 make all the changes for you.

    • & 7 can not be used, it is byte by the condition of the problem. - Vladimir Martyanov
    • 2
      @ Vladimir Martiyanov: Yes, but in case the vehicle wants to generalize the code by selecting the bits in the middle of a byte. Well, or in case of longer data. - VladD
    • @VladD And why not just a & 0b11100000 == 0b110000001 or a & 0xE0 == 0xC0 if suddenly 0b not available. - Mike
    • @Mike: To do this, you need to shift 0b110 to the left, so the number of operations is, in theory, the same. Your path may be preferable if 0b110 is a compile time constant, and the compiler will shift the compile time. But I specifically wrote “One of many ways” :-) - VladD
    • @Vlad Well, perhaps so. I'm just used to interpreting the phrase “check first 3 bits” literally. Plus, an hour ago, the vehicle asked how on its own to find out the length of characters in UTF-8. And it is encoded just by the high bits of the first byte and there are constants. ru.stackoverflow.com/questions/474663/… - Mike