# Check if a bit is set/clear

Hello Dear Friends,

I am trying to find a piece of code that returns true or false if a given bit is set/cleared. For example a 8 bit variable such as an internal register in which I wish to test if bit 7 is set/cleared.

I understand this can be done using bitwise operations bit I'm not sure on the syntax.

Would be much grateful for any help on this.

The simplest way is the bitRead() macro.

``````byte value = 0x43 ;      // some byte that you want to test

byte testbit7 = 0x80 ;   // a byte with only bit 7 set

if ( value & testbit7 )
{
// this part will execute if bit 7 of value is set

}
else
{
// this part will execute if bit 7 of value is not set

}
``````

The reason this works, is that for the "and" operation on two bits to be true, both of the bits must be true (1).

When you make the operation ( value & testbit7 ), the processor calculates the "and" operation for each pair of bits in the two operands. All of the bits in testbit7, except bit 7, are 0, therefore the "and" result for those bit positions will definitely be 0, it doesn't matter what the state of the corresponding bit positions in "value" is. For bit 7, if bit 7 of value is 1, then the bit 7 of the result will be 1, and if bit 7 of value is 0, the result will be zero.

The if statement is then testing for any non-zero value in the result of the "and" operation.

``````boolean isBitSet = (myVariable & (1 << bitIwantToCheck)) ? true : false;
``````

or just

``````boolean isBitSet = myVariable & (1 << bitIwantToCheck);
//If this wasn't a boolean, then it will either be 0 or some power of 2.
//If it is not 0, then the bit is set
``````