Quantcast
Channel: User Alex Lop. - Stack Overflow
Viewing all articles
Browse latest Browse all 39

Answer by Alex Lop. for Check that all bits are set except the Least Significant Bit by using masks

$
0
0

The code you wrote won't check what you expect

if ((myBitfield & 0xFE) == 1)   // 0xFE = 0b11111110{/*yes all bits except the Least Significant is set*/}

More than that, the code inside the if block will never be executed because you clear the least significant bit (LSB) of myBitfield by the & 0xFE operation.

What you are looking for can be implemented by:

if (myBitfield == (uint8_t)~1)   // (uint8_t)~1 = 0b11111110{/*yes all bits except the Least Significant is set*/}

Note that this is not the only way to implement such check. For example, it can also be written as

if (myBitfield == 0xFE)

or

if ((uint8_t)(myBitfield + 2) == 0)  // 0b1111110 + 0b00000010 = 0b1_00000000

and so on...

EDIT

If you meant that you want to check that bit 1 to 7 are set while bit 0 can be anything, you can then "force" this bit (bit 0) to be 0 and compare the result to the mask of all bits set from bit 1 to bit 7 (which is 0xFE):

if ( (myBitfield & 0xFE) == 0xFE)

Of course you also can check against all possible options without applying bitwise operations but the bitwise check looks better, in my opinion, and it also introduces better performance because it has a single branch while the example below contains 2 branches:

if (myBitfield == 0xFE || myBitfield == 0xFF)

Viewing all articles
Browse latest Browse all 39

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>