Set and clear bits
- C course
- Intermediate
- Lesson 101/116
- 5 min
Learn to set and clear specific bits.
Setting and clearing bits
To turn a bit on use bitwise OR (|=); to turn it off use bitwise AND with NOT (&= ~); to toggle use XOR (^=).
Example: flags |= 0x01; sets the first bit. flags &= ~0x01; clears it; ~0x01 makes all bits 1 except the first. flags ^= 0x01; flips the first bit. These three operations are the core of managing bit flags. Each bit is independent; changing one does not affect the others. So one integer can pack many flags tightly.
Managing multiple bits
To manage several bits at once you combine masks. With bitwise OR you can set multiple bits in one operation.
Example: flags |= 0x01; flags |= 0x04; sets the first and third bits. After these, flags is 5 (binary 00000101). Then flags &= ~0x01; clears the first bit; flags stays 4 (binary 00000100). Each operation touches only the relevant bit; the rest are preserved. This is a common pattern in permission systems and state machines.
Practice Set and clear bits
Declare unsigned int flags = 0x00;. Set bits with flags |= 0x01; and flags |= 0x04;. Print with printf("%u\n", flags);. Clear a bit with flags &= ~0x01;. Print with printf("%u\n", flags);.
Starter code
#include <stdio.h>
// Define flags as 0
// Set two bits and print
// Clear one bit and print
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
unsigned int flags = 0x00;
flags |= 0x01;
flags |= 0x04;
printf("%u\n", flags);
flags &= ~0x01;
printf("%u\n", flags);
return 0;
}Expected output
5 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the bit operations
| Term | Meaning |
|---|---|
|= |
Set bit |
&= ~ |
Clear bit |
^= |
Toggle bit |
& |
Test bit |
2 What does flags &= ~0x01 do?
- Makes the value 1
- Resets all bits
- Sets the first bit
- Clears the first bit Correct answer
Explanation: &= ~0x01 zeroes the first bit; the rest are preserved.
3 Complete the bit clear expression
flags &= ~____;
flags &= ~0x01;
Explanation: flags &= ~0x01; clears the first bit.