2

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, isn't the goal to compare the value of a specific (single) bit?

I must be misunderstanding this. What is the correct way to do this?

The Pointer
  • 2,226
  • 7
  • 22
  • 50
  • 3
    http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c-c?rq=1 – Fredrik Pihl Nov 09 '16 at 07:55
  • @FredrikPihl Thanks. They seem to use the shift operators, rather than equalities. In the context of the information from my textbook, what am I doing incorrectly? – The Pointer Nov 09 '16 at 07:58
  • You usually don't compare against the mask after masking, but instead use the result as a boolean, as an enumerated value or what have you. – Ilja Everilä Nov 09 '16 at 08:00
  • @IljaEverilä comparing against the mask checks whether every bit in the mask was set; using result as a boolean checks whether at least one of the bits in the mask was set – M.M Nov 09 '16 at 08:09

2 Answers2

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

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
2

If I understood the question correctly, checking a single bit can be done by using a bit mask that contains the specific bit to test. If the first bit (which corresponds to a value of two) is to be ckecked, one would use

result = flags & 00000010

and afterwards check result, which will be zero if the bit is not set and nonzero if the bit is set. More generalized, one could use

result = flags & (00000001 << i)

where << denotes the shift operator to check the i-th bit.

Codor
  • 17,447
  • 9
  • 29
  • 56