C / CHAPTER 06

Unsigned masks and packed flags

Intermediate

Manipulate selected bits without changing unrelated state.

By the end of this chapter

  • Set clear and test flag masks
  • Separate bitwise from logical operators
  • Keep shifts within the operand width

The idea

Unsigned integers are useful for sets of boolean flags. A mask identifies selected positions: OR sets them, AND with an inverted mask clears them, and XOR toggles them. Testing flags & mask asks whether any masked bit is set; comparing that result with mask asks whether every required bit is set. These are different contracts when the mask contains several bits.

Use unsigned operands for bit manipulation and ensure shift counts are smaller than the promoted operand’s width. A count outside that range is not a portable way to obtain zero. Bitwise operators compute on individual bits, while logical operators convert operands to truth values and may short-circuit. Parenthesize comparisons around masks so operator precedence cannot change the intended test.

C example
#include <stdio.h>
int main(void) {
  unsigned flags = 0u;
  const unsigned READ = 1u, WRITE = 2u, EXECUTE = 4u;
  flags |= READ | WRITE;
  flags &= ~WRITE;
  printf("%u %d\n", flags, (flags & EXECUTE) != 0);
}
Result
1 0

Clearing WRITE leaves READ set, and EXECUTE remains absent.

Try it yourself

Implement checks for any and all requested flags and test a mask containing two bits.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which expression clears bits in mask while preserving other flags?