A standalone bool occupies at least one C++ byte. On common systems that is eight bits, but C++ does not require an eight-bit byte. Bit-packing can save space for very large flag sets, but it also adds masking operations and can complicate concurrency, APIs, and readability.
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.