Data Structures and Algorithms • C# examples
Bit Manipulation and Integer Masks
Use shifts and bitwise operators for compact flags and selected low-level algorithms.
Concept
Bit masks represent sets of a small fixed universe, and bitwise operators combine or test membership efficiently. Shifts and signed integer behavior require care; use an unsigned type when logical right-shift semantics are intended. Prefer readable abstractions unless measurement or the problem naturally calls for bits.
How to approach it
Name masks, constrain the bit width, and test boundary positions and signed values.
Complexity
Most fixed-width bit operations are O(1); enumerating all subsets is O(2ⁿ).
C# example
uint flags = 0;
flags |= 1u << 3; // set bit 3
bool enabled = (flags & (1u << 3)) != 0;
flags &= ~(1u << 3); // clear bit 3
Expected result or behavior
The flag is set, checked, and then cleared using a named bit position.
Practice exercise
Represent permissions as flags and prevent invalid bits from being accepted.
Key takeaway: Bit tricks should be accompanied by explicit width and signedness assumptions.