Bit Manipulation
Set, clear, toggle, and test individual flags.
What is Bit Manipulation?
Bit masks compactly represent independent boolean options inside an unsigned integer.
Important points
- Test empty, single-element, duplicate, and already sorted inputs.
- Separate correctness from optimization.
- Use the standard library in production unless a custom implementation is justified.
C and C++ code examples
#include <stdio.h>
int main(void) {
unsigned flags = 0;
flags |= 1u << 1;
flags |= 1u << 3;
flags ^= 1u << 1;
printf("flags=%u bit3=%u\n", flags, (flags >> 3) & 1u);
}
flags=8 bit3=1
#include <bitset>
#include <iostream>
int main() {
std::bitset<4> flags;
flags.set(1);
flags.set(3);
flags.flip(1);
std::cout << "flags=" << flags
<< " bit3=" << flags.test(3) << '\n';
}
flags=1000 bit3=1
C and C++ comparison
Use unsigned types for predictable shifts. C works directly with integer masks; C++ bitset provides named operations and readable binary output.
Loops, pointers, lengths, and temporary buffers are written explicitly.
Iterators and standard algorithms separate operations from container representation.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Trace each comparison on paper.
- Test duplicates and extreme values.
- Benchmark the custom implementation against the standard library.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Power of Two Check whether a number is a power of two. Easy
- Minimum Elevator Rides Group people into as few weight-limited elevator rides as possible. Hard