Home / Learn Embedded C / Checking If a Bit Is Set
Checking If a Bit Is Set
Reading one bit's state out of a multi-bit value, with AND and a comparison.
How to think about this
Definition
Checking whether bit N is 1 is done with if (register & (1 << N)) — AND-ing with a single-bit mask leaves only that bit's value (0 or the mask itself), which is enough for an if-condition.
Why you need this
Reading one button's state out of an 8-pin input register, or checking one status flag out of a multi-flag status register, both need exactly this isolate-and-test pattern.
How it works
register & (1 << N) produces either 0 (bit was 0) or a non-zero value equal to the mask (bit was 1) — in an if-condition, any non-zero value is "true", so this reads naturally as "if bit N is set".
Where you'll see this
- Reading input registers
- Checking status/flag bits
- Button/switch polling
Try it
This loop checks 4 independent button bits out of one register, one at a time, using the same mask-and-test pattern each time.
Try it: checking a bit and reacting with a ternary
Wrapping the bit test in a ternary is a compact way to turn one flag bit straight into a human-readable result.
Test what you just read
1. What is wrong with "if (register & (1 << N) == 1)" as a way to test whether bit N is set?
Due to C's operator precedence, this parses as register & ((1 << N) == 1), not (register & (1 << N)) == 1.