Lesson 84 of 86IntermediatePro Interactive Lesson

Bit Masks for Testing and Updating Bits

Identify the mask bit positions before applying a bitwise operation.

Core Intuition & How It Works

Bit masks pack boolean flags into a single integer and test, set, clear, or toggle individual bits in O(1) using bitwise AND (&), OR (|), XOR (^), and shifts (<<, >>).

In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.

Time & Space Complexity

MetricComplexity
Time ComplexityO(1) per bitwise op
Space ComplexityO(1)
Topic ChapterChapter 15: Bit Manipulation
Difficulty LevelIntermediate

Key Pattern to Recognize

Test bit k with (x & (1 << k)) !== 0, set with x | (1 << k), clear with x & ~(1 << k), and toggle with x ^ (1 << k).

Common Pitfalls & Edge Cases

Forgetting operator precedence (in most languages, == binds tighter than & or ^) or overflowing 32-bit signed shifts.

Real-World & Technical Interview Applications

Unix file permissions, feature flags, network subnet masks, and bitmask dynamic programming.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.