Practical Uses: Bit Flags and Masking
You'll learn how to pack multiple boolean flags into a single integer using bitwise operations, saving memory and improving efficiency.
The Core Idea
Imagine you need to track several yes/no settings for a user: isAdmin, canEdit, canDelete, and canView. Instead of using four separate boolean variables (or worse, four int values), you can pack all four flags into a single int by assigning each flag to a specific bit position.
Think of an integer's bits like light switches on a panel. Each switch (bit) controls one feature. You can flip individual switches on or off without affecting the others.
How It Works
Each flag gets assigned a unique power-of-two value (a single bit):
int CAN_VIEW = 1; // binary: 0001
int CAN_EDIT = 2; // binary: 0010
int CAN_DELETE = 4; // binary: 0100
int IS_ADMIN = 8; // binary: 1000
Setting flags (turning bits on) uses the | operator:
int permissions = 0;
permissions = permissions | CAN_VIEW | CAN_EDIT; // grants view and edit
Checking flags (reading bits) uses the & operator:
boolean canEdit = (permissions & CAN_EDIT) != 0; // true if edit bit is set
Clearing flags (turning bits off) uses & ~:
permissions = permissions & ~CAN_EDIT; // removes edit permission
This technique is common in system programming, graphics libraries, and anywhere memory efficiency matters. You're storing four booleans in the space of one integer!
Key Takeaway: Bitwise operations let you pack multiple boolean flags into a single integer by treating each bit as an independent on/off switch, which you manipulate using | to set, & to check, and & ~ to clear.