Bit masking is a technique used in C to manipulate specific bits within a data type (e.g., integer) using bitwise operators like &
, |
, ^
, and ~
.
- Common Use Cases:
- Setting a bit:
num |= (1 << pos)
- Clearing a bit:
num &= ~(1 << pos)
- Toggling a bit:
num ^= (1 << pos)
- Checking a bit:
(num & (1 << pos)) != 0
- Setting a bit:
It is widely used for tasks like flags, permissions, and compact data storage.