Bit Manipulation
Bit masks compactly represent independent boolean options inside an unsigned integer.
What is Bit Manipulation?
Bit masks compactly represent independent boolean options inside an unsigned integer.
Set, clear, toggle, and test individual flags.
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
main.c
#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
C++
main.cpp
#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.
C
Loops, pointers, lengths, and temporary buffers are written explicitly.
C++
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.