In this lesson, you will learn how to pack multiple true/false settings into a single integer using bitwise operators to save space and organize your data.
The Concept of Bit Flags
Imagine you are building a simple video game character. You need to keep track of three states: is the character visible, invincible, or frozen? Instead of creating three separate variables, we can represent each state as a specific "bit" in one integer.
Think of an integer as a row of lightbulbs. We assign a specific position to each state using powers of two:
VISIBLE= 1 (binary001)INVINCIBLE= 2 (binary010)FROZEN= 4 (binary100)
Manipulating Flags
We use bitwise operators to change these states without affecting the other bits.
1. Setting a flag (The OR operator |)
To turn on a flag, use the bitwise OR (|). This forces the specific bit to 1 regardless of its current state.
state = 0
state = state | 1 # State is now 1 (Visible is ON)
2. Testing a flag (The AND operator &)
To check if a flag is on, use the bitwise AND (&). If the result is not zero, the bit is set.
if state & 1:
print("Character is visible!")
3. Clearing a flag (The AND NOT combination)
To turn a flag off, we use a bitwise AND combined with a bitwise NOT (~). This flips the bits of the flag we want to remove, then ANDs it against our state to clear only that specific position.
state = state & ~1 # Turns off the Visible flag
4. Toggling a flag (The XOR operator ^)
If you want to flip a switch (on to off, or off to on), use the bitwise XOR (^).
state = state ^ 2 # Flips the Invincibility flag
By using these operations, you can maintain a "compact state" where a single integer acts as a collection of independent boolean switches. This is a memory-efficient way to manage settings in your programs.
Key Takeaway: Use the OR (|) operator to set bits, AND (&) to test them, AND NOT (& ~) to clear them, and XOR (^) to toggle them, all while keeping your data stored in one efficient integer.