</>EmbeddedInterview

What is a bit mask and how is GENMASK built?

MediumBit Manipulation

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 << l gives ones from bit l upward: for l = 4, 0xFFFFFFF0.
  • ~0u >> (31 - h) gives ones from bit h downward: for h = 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) and USART_CR1_UE_Msk (mask).
  • Linux: GENMASK(), BIT(n), FIELD_PREP(), FIELD_GET(), and GENMASK_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.