Topics / Bit Manipulation / Q23
What is a bit mask and how is GENMASK built?
Short answer: A mask is a constant whose 1 bits select the bits you want to read or change. GENMASK(h, l) builds a contiguous run of ones from bit l to bit h (inclusive) by shifting all-ones, which avoids the undefined 1u << 32.
#define GENMASK(h, l) (((~0u) << (l)) & (~0u >> (31 - (h))))
/* GENMASK(7, 4) == 0x000000F0 */
/* GENMASK(31, 0) == 0xFFFFFFFF (no overflow) */
How it is built
~0u << lgives ones from bitlupward: forl = 4,0xFFFFFFF0.~0u >> (31 - h)gives ones from bithdownward: forh = 7,0x000000FF.- AND keeps the overlap: bits 7..4,
0x000000F0.
Why not ((1u << (h - l + 1)) - 1) << l? For a full 32-bit field, h - l + 1 == 32, and 1u << 32 is undefined behaviour. With GENMASK every shift amount stays in the range 0..31.
Using masks
| Operation | Code |
|---|---|
| set the bits | x |= MASK |
| clear the bits | x &= ~MASK |
| toggle | x ^= MASK |
| all set? | (x & MASK) == MASK |
| any set? | (x & MASK) != 0 |
| read field | (x & MASK) >> l |
Naming conventions in real code
- CMSIS:
USART_CR1_UE_Pos(bit position) andUSART_CR1_UE_Msk(mask). - Linux:
GENMASK(),BIT(n),FIELD_PREP(),FIELD_GET(), andGENMASK_ULL()for 64-bit.
Follow-up: "Why ~0u and not ~0?" ~0 is -1 as a signed int, and shifting a negative value left is undefined. ~0u is unsigned.