Bit Masking
A bit mask selects, sets, or clears specific bits of a value using bitwise operations.
What a mask is
A mask is an integer whose bits mark positions of interest. Combined with AND, OR, or XOR, it isolates or modifies exactly those bits while leaving the rest untouched.
Reading fields
To extract a field, shift it down to the low bits and AND with a mask of ones the width of the field. To read bits 4–7 of x: (x >> 4) & 0xF.
Setting and clearing
OR with a mask sets the marked bits to 1. AND with the complement of a mask clears them to 0. XOR with a mask toggles them. These three cover most field manipulation.
Flags in one integer
Many small booleans can be packed into a single integer, one bit each. A permission set or a set of options becomes a compact value that is tested and combined with bitwise operators — the pattern behind Unix file modes.
Packing structures
Hardware registers and compact file formats pack several fields into one word. Masking and shifting read and write each field without disturbing its neighbors, which is essential for device drivers and protocol parsers.
FLAG_READ, FLAG_WRITE, FLAG_EXEC = 1, 2, 4
perms = FLAG_READ | FLAG_WRITE
print(bool(perms & FLAG_WRITE)) # True
perms &= ~FLAG_WRITE # clear write
print(bool(perms & FLAG_WRITE)) # False