The Pointer The Pointer - 29 days ago 12
C Question

Checking the value of a bit in C

I am learning how to check the value of a bit. My textbook claims the following.

'Even if bit 1 in

flags
is set to 1, the other bit setting in
flags
can make the comparison untrue. Instead, you must first mask the other bits in
flags
so that you compare only bit 1 of
flags
with
MASK
:'

if ((flags & MASK) == MASK)
puts("Wow!");


I'm having trouble understanding this concept.

For instance, let
flags = 00001111
and
MASK = 10110110
.

Therefore,
flags & MASK = 00000110
.

If we now compared
MASK
and
00000110
, we would be comparing bits 2 and 3. However, I isn't the goal to compare the value of a specific (single) bit?

I must be misunderstanding this. I would appreciate it if someone could clarify my misunderstanding and explain the correct way to do this.

Thank you.

AnT AnT
Answer
  1. Condition (flags & MASK) != 0 checks whether any of the flags's bits specified by MASK are set to 1.

  2. Condition (flags & MASK) == MASK checks whether all of the flags's bits specified by MASK are set to 1.

Symmetrically

  1. Condition (flags & MASK) == 0 checks whether all of the flags's bits specified by MASK are set to 0.

  2. Condition (flags & MASK) != MASK checks whether any of the flags's bits specified by MASK are set to 0.

Choose the one you need in each particular case.

If you need to check just a single bit (i.e. MASK contains only one bit set to 1), then conditons 1 and 2 are equivalent (and conditons 3 and 4 are equivalent as well).

It is not entirely clear from the text you quoted whether MASK can contain more than one bit set to 1.