Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality operator versus bitwise AND operator usage

In C language, I often see if statements in such form:

#define STATUS 0x000A
UINT16 InterruptStatus;
if (InterruptStatus & STATUS)
{
 <do something here....>
}

If I had this statement, would it be any different in processing time or any other reason why this would not be the preferred/alternative way?

#define STATUS 0x000A
UINT16 InterruptStatus;
if (InterruptStatus == STATUS)
{
 <do something here....>
}
like image 866
newb7777 Avatar asked Aug 02 '26 05:08

newb7777


2 Answers

Well, they are not the same.

In case of a bitwise AND, two different values of operands can produce a true, whereas for equality, both must be same.

Consider decimal value 5 and 3 as operands.

  • Bitwise AND will produce a TRUE value for condition check ( 5 & 3 == 1).
  • Equality will produce a FALSE value (5 ==3 ==> false)

So they are not alternatives, really.

Bitwise operations are widely used to check a particular bit of a flag variable to be "set" or "unset".

like image 55
Sourav Ghosh Avatar answered Aug 05 '26 12:08

Sourav Ghosh


This can be used for checking if some number has some bits set or not, so it is different from equality.

Assume you have some number represented in binary as 0b00010001

And you want to check if bit number 4 is set, so you need to do

if(0b00010001 & 0b00010000)
 // do something.

So not necessarily the two numbers above are equal - however, using above check you can verify if 4th bit is set on the 0b00010001 number.

like image 29
Giorgi Moniava Avatar answered Aug 05 '26 13:08

Giorgi Moniava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!