Bit masking
- C course
- Intermediate
- Lesson 100/116
- 5 min
Learn flag management with bit masking.
Bit masking
Bit masking uses bitwise AND (&) to select specific bits of a value. A mask is a number with 1s only at the bits of interest.
Example: flags & 0x02 tests the second bit of flags. A non-zero result means the bit is set; zero means it is clear. 0x02 is 00000010 in binary; only the second bit is 1. This pattern is the standard way to inspect hardware registers and permission flags. Each flag lives in its own bit, so one integer packs many states tightly.
Condition with bitwise AND
You can use the mask result in an if condition to branch on the bit state. Non-zero means true; zero means false.
Example: if (flags & mask) printf("on\n"); else printf("off\n");. Here, if flags & mask is non-zero, "on" is printed; if zero, "off". In C any non-zero value is true; so you can use the bitwise AND result directly as a condition. This structure appears constantly in hardware drivers and embedded systems; you use it to read a pin or check a flag.
Practice Write a bit masking program
Declare unsigned int flags = 0x0F; and unsigned int mask = 0x02;. Check with if (flags & mask); if true print printf("açık\n");, else print printf("kapalı\n");.
Starter code
#include <stdio.h>
// Define flags and mask variables
// Check with bitwise AND
// Print "açık" or "kapalı"
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
unsigned int flags = 0x0F;
unsigned int mask = 0x02;
if (flags & mask) {
printf("açık\n");
} else {
printf("kapalı\n");
}
return 0;
}Expected output
açık
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does flags & 0x02 test?
- Whether the second bit is set Correct answer
- Whether flags equals 2
- The total bit count
- The sign bit
Explanation: 0x02 has only the second bit as 1; AND tests that bit.
2 Complete the bitwise AND condition
if (flags & ____) printf("açık
");
if (flags & mask) printf("açık
");
Explanation: flags & mask tests the masked bit.
3 Match the masking parts
| Term | Meaning |
|---|---|
& |
Bitwise AND |
0x02 |
Second-bit mask |
flags |
Tested value |
!= 0 |
Bit is set |