Quiz Entry - updated: 2026.07.14
What are the common bit mask patterns and how do you create them?
Build masks with shifts: 1 << n sets a single bit at position n, and (1 << n) - 1 makes the low n bits all 1s.
Common mask patterns:
| Pattern | Formula | 8-bit Example |
|---|---|---|
| Single bit at position n | 1 << n |
1 << 3 = 00001000 |
| n low bits set | (1 << n) - 1 |
(1 << 4) - 1 = 00001111 |
| n high bits set | ~((1 << (w-n)) - 1) |
n=4: 11110000 |
| All bits set | ~0 or -1 |
11111111 |
| Bits [hi:lo] set | ((1 << (hi-lo+1)) - 1) << lo |
[5:2]: 00111100 |
Why (1 << n) - 1 gives n ones:
1 << 4 = 00010000 (16)
(1 << 4)-1 = 00001111 (15, four 1s!)
Practical examples:
// Get lower 4 bits (nibble)
low_nibble = value & 0x0F; // & 00001111
// Get upper 4 bits of a byte
high_nibble = (value >> 4) & 0x0F;
// Check if bit 7 is set
if (value & (1 << 7)) { ... }
// Clear bits 4-6
value &= ~(0x70); // & 10001111
// Set bits 0-3 to a value (0-15)
result = (original & ~0x0F) | new_value;
Tip: Drawing out the binary pattern helps when designing masks. 4 bits = 1 hex digit.
Go deeper:
Mask (computing) (Wikipedia) — using bitmasks to set, clear, toggle, and extract bits.