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.
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.
Related Resources
Tutorial
Bitwise Operators in Python
Learn how to use Python's bitwise operators to manipulate individual bits of data at the most granular level.
For additional information on related topics, take a look at the following resources:
- Binary, Bytes, and Bitwise Operators in Python (Course)
- Bytes Objects: Handling Binary Data in Python (Tutorial)
- Build Enumerations of Constants With Python's Enum (Tutorial)
- Python Booleans: Use Truth Values in Your Code (Tutorial)
- Python's Bytearray: A Mutable Sequence of Bytes (Tutorial)
- Bitwise Operators in Python (Quiz)
- Python Bytes (Quiz)
- Building Enumerations With Python's enum (Course)
- Build Enumerations of Constants With Python's Enum (Quiz)
- Python Booleans: Leveraging the Values of Truth (Course)
- Python's Bytearray (Quiz)
By Martin Breuss • Updated July 27, 2026