Skip to content

bitmask

A bitmask is an integer whose individual bits act as independent on/off flags, letting a single value pack many Boolean options together. Each bit position stands for one option, so a bitmask modeling file permissions might reserve one bit for read, one for write, and one for execute. Programs read and change these flags with bitwise operators instead of keeping a separate variable for each.

Four everyday tasks cover most bitmask work, and each one changes only the bits the mask selects, leaving the rest alone:

  • Setting a bit ORs the value with a mask whose chosen bits are 1.
  • Clearing a bit ANDs the value with a mask whose chosen bits are 0.
  • Toggling a bit XORs the value with the mask.
  • Testing a bit ANDs the value with a single-bit mask and checks the result against zero.

Flip the value and mask bits in the explorer below, choose one of these operations, and watch which bits the result changes.

Interactive diagram — enable JavaScript to view.

Bitmasks turn up wherever compact, fast flag handling matters, such as Unix file modes, hardware and CPU status registers, graphics APIs like OpenGL, and network address masks. In Python, the operators &, |, ^, ~, <<, and >> apply to ordinary int values, and hexadecimal literals like 0xFF map cleanly onto the bit groups a mask targets.

Bitwise Operators in Python

Tutorial

Bitwise Operators in Python

Learn how to use Python's bitwise operators to manipulate individual bits of data at the most granular level.

intermediate python

For additional information on related topics, take a look at the following resources:


By Martin Breuss • Updated July 27, 2026