简体   繁体   中英

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.

  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 (ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM