In embedded systems, multiple configuration fields are often packed into a single register using bit-level operations.
You are given the following field specifications to be packed into a 16-bit control register:
| Field | Bits | Position (LSB-first) |
| Mode | 3 | Bits 0β2 |
| Speed | 5 | Bits 3β7 |
| Reserved | 2 | Bits 8β9 (must be 0) |
| Status | 6 | Bits 10β15 |
Your task is to:
Example-1
Input: mode = 3, speed = 10, status = 12
Output: 12371
(Hex: 0x3053, Binary: 0011000001010011)Example-2
Input: mode = 7, speed = 31, status = 63
Output: 64767
(Hex: 0xFCFF, Binary: 1111110011111111)Example-3
Input: mode = 4, speed = 16, status = 8
Output: 8324
(Hex: 0x2084, Binary: 0010000010000100)
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
| Bits | Field Name |
|---|---|
| 15 β 12 | Mode |
| 11 β 8 | Speed |
| 7 β 0 | Flags |
To work with them, we need two core skills:
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 ModeExtract 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 bitsThis is why precise extraction and modification using bit masks is a core embedded skill.