Bit Manipulation / CoreBit MaskingEasy

Bit Masking — Set, Clear, Toggle, Check

Use bitwise operators with masks to manipulate individual bits. Foundation of all bit manipulation.

LC
Practice on LeetCode 191: Number of 1 Bits
Open Problem

What does it solve?

Bit masking lets you manipulate individual bits of a number. Create a mask with 1 << pos, then combine with AND, OR, XOR to check, set, clear, or toggle any bit.

Four Operations

Set bit: n | (1 << pos)
Clear bit: n & ~(1 << pos)
Toggle: n ^ (1 << pos)
Check: (n >> pos) & 1

🔧 Interactive Bit Playground

13=0xD

Click bits to toggle directly

Bit position:
Click an operation above or toggle bits directly.
C++ — Bit Masking Operations
// Set bit at position pos
n = n | (1 << pos);

// Clear bit at position pos
n = n & ~(1 << pos);

// Toggle bit at position pos
n = n ^ (1 << pos);

// Check if bit at pos is set
bool isSet = (n >> pos) & 1;

// Count set bits (Kernighan's algorithm)
int countBits(int n) {
    int count = 0;
    while (n) {
        n &= (n - 1);  // clear lowest set bit
        count++;
    }
    return count;
}
Complexity
Time (per op)
O(1)

Each bit operation is constant time.

Count Bits
O(K)

K = number of set bits (Kernighan's).


📝 Notes

▼