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.
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.
flags = 0b0101. Which value results from setting bit 1 (mask 0b0010)?
A file's owner permission is 6. Can the owner execute it?
Which operation clears bit 2 of flags whether or not it was already set?
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 << kbuilds a single-bit mask. - The trap: XOR flips, so it is not a safe way to clear a flag.
