Skip to the workspace
Pebellslearn by building
Bitwise Operators  ›  Capstone Project

Masks and Flags

Bitwise Operators 12 minA mask is a number whose 1 bits pick out the flags you care about, and combining it with OR, AND NOT, XOR or AND sets, clears, flips or tests just those bits.

computer science / Masks and Flags

Explore each scene at your own pace.

01 · The rule

The rule

Masks and Flags

Run ls -l on a Linux machine and you see permissions like rwxr-x---. Behind them sit plain numbers such as 750. Games store "has key, has shield, is invisible" in one integer. Network packets pack eight flags into a single byte. All of these use the same four moves on bits, which make up the capstone of this section.

The rule

Set with OR, clear with AND NOT, flip with XOR, test with AND.

A flag is one bit that means one yes/no fact. A mask is a number with 1s exactly at the bits you want to touch, usually built with 1 << k or written directly: 0b0100, 4.

Goal Operation Why it works
Set a flag flags OR mask OR with 1 forces a 1; OR with 0 leaves bits alone
Clear a flag flags AND NOT mask AND with 0 forces a 0; AND with 1 leaves bits alone
Flip a flag flags XOR mask XOR with 1 flips; XOR with 0 leaves bits alone
Test a flag flags AND mask non-zero means the flag is on

In code, that is flags | mask, flags & ~mask, flags ^ mask and flags & mask.

Unix permissions are a perfect example: for each of owner, group and others, read = 4, write = 2, execute = 1. 7 = 4 + 2 + 1 is rwx, 6 is rw-, 5 is r-x, 4 is r--. Masks can also pick out a group of bits at once: x & 0xF keeps only the lowest four bits (one hex digit) of x.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.