26. Extract and Modify Field in a 32-bit Register

In embedded systems, a 32-bit configuration register often contains several packed fields. 

Your task is to extract a 5-bit field located at bit positions 10 to 14 from a 32-bit register value. 

If this field’s value is less than 31, increment it by 1. Then write the updated value back to the same bit positions in the register, leaving all other bits unchanged.

Use only bitwise operations to extract, modify, and update the register.

Bit layout example (bit 0 is LSB):

Register: [31 ... 15 | 14 13 12 11 10 | 9 ... 0]
                        ↑  ↑  ↑  ↑  ↑ (target field)

 

Example-1

Input: 0x00003C00
Output: 0x00004000

(Field at bits 10–14 was 0x1E = 30 → incremented to 31)


Example-2

Input: 0x00000000
Output: 0x00000400

(Field was 0 → becomes 1)
 

Example-3

Input: 0x00007C00
Output: 0x00007C00

(Field was 31 → remains unchanged)


 

Need Help? Refer to the Quick Guide below

In embedded systems, a single register often contains multiple fields, each controlling a different function. These fields are packed into specific bit positions.

Example: A 16-bit Control Register

BitsField Name
15 – 12Mode
11 – 8Speed
7 – 0Flags

To work with them, we need two core skills:

  1. Extracting a field (reading the bits at a specific position)
  2. Replacing or updating that field (without touching other bits)
     

This is done using bit masking and bit shifting.

To extract Speed field (bits 8 to 11):

uint16_t speed = (reg >> 8) & 0x0F;

To update the Mode field (bits 12 to 15):

reg &= ~(0x0F << 12);         // Clear Mode bits
reg |= ((new_mode & 0x0F) << 12); // Set new Mode

Key Operations

Extract a bit field

value = (reg >> position) & mask;

Replace a bit field

/* Where mask is a binary mask for the number of bits in the field.
E.g., For 3-bit field → mask = 0x07 */


reg &= ~(mask << position);            // Clear the bits (mask= high bits)
reg |= ((new_value & mask) << position); // Set the new bits

Relevance in Embedded/Firmware

  • Most hardware registers (UART, Timer, ADC, SPI) use bit fields to define different parameters.
  • Peripheral setup often involves:
    • Extracting status bits (e.g., data ready, error)
    • Modifying specific bits (e.g., set baud rate, enable TX)
  • It’s unsafe to overwrite the entire register — instead, we update only the target bits.

This is why precise extraction and modification using bit masks is a core embedded skill.