Bitmask Flag Management

Master the four essential bitmask operations: set, clear, toggle, and check a specific bit. The foundation of flag-based programming in systems and applications.

Bitmask Patterns

Detailed Explanation

The Four Bitmask Operations

Flag-based programming uses individual bits within an integer to represent boolean states. Four operations form the complete toolkit for managing these flags.

1. Set a Bit (turn ON)

Use OR with a mask that has a 1 at the target position:

value = value | (1 << bitPosition);
// Shorthand: value |= (1 << bitPosition);

Example: Set bit 3 of 0b00001010:

  0b00001010
| 0b00001000  (1 << 3)
──────────────
  0b00001010   (bit 3 was already set, no change)

2. Clear a Bit (turn OFF)

Use AND with the NOT of the mask:

value = value & ~(1 << bitPosition);
// Shorthand: value &= ~(1 << bitPosition);

Example: Clear bit 1 of 0b00001010:

  0b00001010
& 0b11111101  (~(1 << 1))
──────────────
  0b00001000

3. Toggle a Bit (flip)

Use XOR with the mask:

value = value ^ (1 << bitPosition);
// Shorthand: value ^= (1 << bitPosition);

4. Check a Bit (read)

Use AND and compare to zero:

const isSet = (value & (1 << bitPosition)) !== 0;

Multiple Flags at Once

All four operations work with multi-bit masks. Set bits 0 and 2 simultaneously:

const MASK = (1 << 0) | (1 << 2);  // 0b00000101
value |= MASK;   // Set both
value &= ~MASK;  // Clear both
value ^= MASK;   // Toggle both

Use Case

Operating system kernels use bitmask flags extensively for process states, file descriptors, and memory page attributes. In Linux, the `open()` system call accepts flags like O_RDONLY (0), O_WRONLY (1), O_RDWR (2), O_CREAT (0x40), O_TRUNC (0x200) combined with OR. The kernel then checks individual flags with AND to determine the requested behavior.

Try It — Bitwise Calculator

Open full tool