Bitmask
Prerequisites
1. What is Bitmask?
Bitmasking is a technique that uses bits of an integer to represent multiple states. You can manage multiple boolean values using a single integer.
Example:
Each bit represents a state:
1
2
3
| bit: 3 2 1 0
↓ ↓ ↓ ↓
value: 1 0 1 1
|
2. Why use Bitmask?
✔ Memory efficient
✔ Very fast operations (bitwise)
✔ Great for representing combinations of states
👉 Common use cases:
- Subsets
- Visited checks (DFS/BFS)
- DP with state compression
3. How to use Bitmask
3-1. ON/OFF
✔ Turn ON a bit
✔ Turn OFF a bit
✔ Toggle a bit
✔ Check a bit
1
2
3
4
| if (mask & (1 << i))
{
// i-th bit is ON
}
|
✔ Reset all bits
3-2. Management Enum
1
2
3
4
5
6
7
8
9
10
11
12
| enum EStatus
{
EStatus_None = 0x00,
EStatus_Left = 0x01, // 0b00001
EStatus_Top = 0x02, // 0b00010
EStatus_Right = 0x04, // 0b00100
EStatus_Bottom = 0x08 // 0b01000
EStatus_LT = EStatus_Left | EStatus_Top, // 0b00011
EStatus_LR = EStatus_Left | EStatus_Right, // 0b00101
EStatus_LB = EStatus_Left | EStatus_Bottom, // 0b01001
....
}
|