Question.4
A UART control register has the following 8-bit layout:
| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|
| — | PARITY | BAUD | EN | ||||
The register currently holds 0x1F. A developer needs to change the BAUD field to 3 without affecting other bits.
Code A:
reg &= ~(0x07 << 1);
reg |= (3 << 1);Code B:
reg &= ~(0x07 << 1);
reg |= (3 << 2);Code C:
reg = (reg & 0xF1) | (3 << 1);Code D:
reg |= (3 << 1);Which code(s) is/are correct?
Note: Multiple options may be correct.
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.