In embedded systems, registers are often configured by setting specific bits. To make the code cleaner and reusable, firmware developers use macros to set fields in a register.
You are given a 16-bit control register layout:
| Field | Bits | Position (LSB-first) |
| ENABLE | 1 | Bit 0 |
| MODE | 2 | Bits 1–2 |
| SPEED | 3 | Bits 3–5 |
| RESERVED | 2 | Bits 6–7 (must be 0) |
Your task is to:
Example-1
Input: enable = 1, mode = 2, speed = 4
Output: 37
(Binary: 0000 0000 0010 0101)Example-2
Input: enable = 0, mode = 1, speed = 3
Output: 26
(Binary: 0000 0000 0001 1010)
In C, bitwise operations allow direct manipulation of individual bits within a byte, word, or register. These operations are performed using the following operators:
Common bit-masking patterns:
reg |= (1 << n); // Set bit n
reg &= ~(1 << n); // Clear bit n
reg ^= (1 << n); // Toggle bit n
if (reg & (1 << n)) // Check if bit n is setThese operations are used to target and modify only specific bits, without disturbing others.
| Bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| Value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
E.g.
reg |= (1 << 3)reg &= ~(1 << 6) reg & (1 << 0)reg ^= (1 << 3)Bitwise techniques apply the same way for uint32_t types — often used in 32-bit MCUs for status/configuration registers.
Example:
ctrl_reg |= (1U << 23); // Set bit 23 in a 32-bit control register
1 << n must be inside parentheses during masking:reg |= (1 << 4) vs ❌ reg |= 1 << 4 & 0xFuint8_t, uint16_t, or uint32_t.reg = (1 << 2); // WRONG: overwrites entire register
reg |= (1 << 2); // RIGHT: sets only the 2nd bit