0Pricing
C Academy · Lesson

Bit Masks and Flags

Set, clear, toggle bits.

Bits as Flags

A single integer can store many on/off settings, one per bit. Each bit is a flag.

This is compact and fast, common in operating systems and embedded code.

#include <stdio.h>

int main(void) {
    unsigned flags = 0;
    printf("Initial flags = %u\n", flags);
    return 0;
}

Defining Masks

A mask is a value with specific bits set. Define each flag as a power of two so it occupies its own bit.

#include <stdio.h>

#define READ  (1u << 0)
#define WRITE (1u << 1)
#define EXEC  (1u << 2)

int main(void) {
    printf("READ=%u WRITE=%u EXEC=%u\n", READ, WRITE, EXEC);
    return 0;
}

All lessons in this course

  1. Bitwise Operators
  2. Shifts
  3. Bit Masks and Flags
  4. Practical Bit Tricks
← Back to C Academy