Course contentsShow
← C
Lesson 189 of 1,2193. Operators and ExpressionsFree lesson

Using bitwise operators for flags

Using bitwise operators for flags

What you'll learn: How to efficiently pack multiple true/false settings into a single integer using bitwise operations.

Imagine you are developing a video game. You need to track a player’s status: Are they poisoned? Can they fly? Are they invisible? Do they have a shield?

Normally, you might create four separate bool variables. However, in low-level programming or systems where memory is tight, we use a single integer as a "container" for these flags. Since an int consists of many bits (0s and 1s), we can treat each individual bit as its own independent toggle switch.

Defining the Masks

To talk to a specific bit, we define "masks" using powers of two. Each number represents a different bit position:

#define POISONED  1 // 0001
#define CAN_FLY   2 // 0010
#define INVISIBLE 4 // 0100
#define SHIELDED  8 // 1000

Setting and Checking Flags

We use the bitwise OR (|) to "turn on" a flag and the bitwise AND (&) to "check" a flag.

Think of the OR operator like adding a key to a keychain. If you OR your status with CAN_FLY, that specific bit flips to 1, regardless of what else is there. Think of the AND operator like a specialized scanner: it ignores everything except the bit you are asking about.

#include <stdio.h>

int main() {
    unsigned char playerStatus = 0; // All flags off (0000)

    // Set flags using OR
    playerStatus |= CAN_FLY;    // Now 0010
    playerStatus |= SHIELDED;   // Now 1010

    // Check flags using AND
    if (playerStatus & CAN_FLY) {
        printf("The player is soaring through the clouds!\n");
    }

    if (!(playerStatus & POISONED)) {
        printf("The player is healthy.\n");
    }

    return 0;
}

Why do this?

Using flags is incredibly fast for the CPU. Instead of passing four or eight different variables to a function, you pass one single number. It also makes it easy to save a complex state to a file; you only have to write one value to disk to remember exactly which combination of dozens of settings were active.

Key takeaway

Bitwise flags allow you to store multiple boolean states in one variable by using | to turn bits on and & to check their status.