Bitmasking is a technique used in computer science and programming to manipulate individual bits of data. It involves using a mask, typically a binary number, to isolate, set, clear, or toggle specific bits within another binary number. It’s often used for tasks like checking flags, performing bitwise operations, and optimizing memory usage.
Here’s a basic rundown of the operations you can perform using bitmasking:
- AND (
&
): To check if certain bits are set (i.e., equal to 1).- Example: To check if the 3rd bit is set, you could apply a mask like
0b100
(which is4
in decimal) and performnumber & 0b100
.
- Example: To check if the 3rd bit is set, you could apply a mask like
- OR (
|
): To set specific bits (i.e., turn them to 1).- Example:
number | 0b100
would set the 3rd bit to 1, leaving other bits unchanged.
- Example:
- XOR (
^
): To toggle specific bits (flip them between 1 and 0).- Example:
number ^ 0b100
would flip the 3rd bit.
- Example:
- NOT (
~
): To invert all bits (turn 1s to 0s and vice versa).- Example:
~number
flips every bit ofnumber
.
- Example:
- Shift operators (
<<
,>>
): To shift bits left or right, effectively multiplying or dividing by powers of 2.
Bitmasking is efficient and often used in scenarios like representing flags or settings with individual bits, such as in graphics programming, networking, or managing permissions.