I want to take you down to the binary level where memory is scarce. In high level languages, programmers use bool variables to represent true/false states. In C++, a single bool consumes a full byte (8 bits) of memory because the CPU cannot address individual bits directly.
If you have eight boolean flags in your game engine or network package, storing them as separate booleans wastes 64 bits of space. Using bitwise operations, we can pack all eight states into a single byte, saving memory bandwidth and cache space.
The Bitwise Operators
Bitwise operators manipulate the binary bits of variables directly:
* AND (&): Returns 1 if both bits are 1.
* OR (|): Returns 1 if at least one bit is 1.
* XOR (^): Returns 1 if the bits are different.
* NOT (~): Flips all bits (0 becomes 1, 1 becomes 0).
* Left Shift (<<): Shifts bits to the left, padding with zeros.
* Right Shift (>>): Shifts bits to the right.
Bitmasking: Packing State Flags
We can assign specific bit positions to represent different states in our application. These are called bit masks. Let's see how we can pack, set, clear, and check flags inside a single byte:
Compacting Your Memory footprint
Bitmasking is like folding your clothes tightly before packing a suitcase. Instead of throwing each shirt in loose (wasting entire sections of cache memory), you fold them into tiny, specific coordinates. In high performance rendering pipelines and networking protocols, bitmasking is the standard way to transmit packets and manage options efficiently.