newb7777
newb7777

Reputation: 563

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....>
}

Upvotes: 3

Views: 2204

Answers (5)

sreepurna
sreepurna

Reputation: 1662

Both are different.

== is a relational operator

& is a bit wise operator

From tutorials point:

== : Checks if the values of two operands are equal or not. If yes, then the condition becomes true.

& : Binary AND Operator copies a bit to the result if it exists in both operands.

For example:

A= 12 , B =13

A == B: produces output as false as these two are different

A & B: Output will be true

A = 0000 1100

B = 0000 1101

A&B = 0000 1100 -> which is 12 and it is a valid integer.so condition will be true

Upvotes: 0

newb7777
newb7777

Reputation: 563

Top one will be logically true if any one of the bit matches, 0x000A. it doesn't have to exactly equal 0x000A; it could be true if

if ((InterruptStatus == 0x0008) || (InterruptStatus == 0x0002))

The bottom code makes sure it is absolutely equal to 0x000A.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

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".

Upvotes: 5

zahirdhada
zahirdhada

Reputation: 405

& is a bitwise AND operator. It is used to check if a bit at a certain position is on or not.

== is an equality operator which returns true only if the values of both operands match exactly.

For more on operators in C: https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

Upvotes: 1

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

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.

Upvotes: 2

Related Questions