Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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.

The shortcut

For each job, say the verb and reach for its operator: set → OR, clear → AND NOT, flip → XOR, test → AND. Then work the columns under the mask only; everything else is untouched.

Changing permission 5 (r-x)Step 1 of 4
  1. Test write

    5 AND 2 = 101 AND 010 = 000. Zero, so no write permission.

The trap: clearing with XOR. XOR flips, so if the flag was already off, XOR turns it on. Use AND NOT when you mean "make sure it is off".

Drills

Answer fast — trust the rule.

quick drill

flags = 0b0101. Which value results from setting bit 1 (mask 0b0010)?

quick drill

A file's owner permission is 6. Can the owner execute it?

quick drill

Which operation clears bit 2 of flags whether or not it was already set?

quick drill

What is 0xAB AND 0xF?

Remember

  • Set with OR, clear with AND NOT, flip with XOR, test with AND.
  • A mask has 1s only where you want to act; 1 << k builds a single-bit mask.
  • The trap: XOR flips, so it is not a safe way to clear a flag.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainReading and changing permissions

Unix permission bits use read = 4, write = 2, execute = 1 for each user class. A file's owner has permission 5. Explain what 5 means, show how to test whether the owner can write, how to grant write, and how to then remove execute, giving the value after each step.