Bitwise operations and hardware registers
Using masks and the bitwise operators to set, clear, toggle and test individual bits, and reading a datasheet's register map to control hardware.
Lesson 3 of 6 · 35 min · Self-paced · Free
One number, many switches
Inside a microcontroller, a single 8-bit control register might hold eight unrelated settings: bit 0 switches a timer on, bit 1 enables its interrupt, three more bits choose its speed. To change one setting without disturbing the others, you need to work on individual bits. C's bitwise operators do exactly this, and they appear in almost every piece of firmware that talks to hardware. You met binary and hexadecimal in the digital electronics module; now you will use them.
The bitwise operators
Bitwise operators work on each bit position independently, using the logic gates you already know.
operator name example (binary) result
& AND 1100 & 1010 1000
| OR 1100 | 1010 1110
^ XOR 1100 ^ 1010 0110
~ NOT ~1100 (in 4 bits) 0011
<< shift left 0001 << 2 0100
>> shift right 1000 >> 3 0001Do not confuse & with && or | with ||. The doubled versions are logical operators that treat a whole value as true or false. 6 & 1 is 0, but 6 && 1 is 1.
Masks
A mask is a number with 1s in exactly the bit positions you care about. The easiest way to make a mask for bit n is to shift a 1 into place:
1u << 0 = 0000 0001 (bit 0)
1u << 3 = 0000 1000 (bit 3)
1u << 7 = 1000 0000 (bit 7)The u makes the 1 unsigned, which avoids undefined behaviour when shifting into the top bit of a signed value.
The four essential moves
With a register value reg and a mask m:
- Set the bits in m (make them 1):
reg |= m;OR with 1 forces a 1; OR with 0 leaves a bit alone. - Clear the bits in m (make them 0):
reg &= ~m;~mhas 0s only where m has 1s, and AND with 0 forces a 0. - Toggle the bits in m:
reg ^= m;XOR with 1 flips a bit; XOR with 0 leaves it. - Test whether a bit is set:
if (reg & m). The result is non-zero only if that bit is 1.
These are read-modify-write operations: read the whole register, change some bits, write the whole value back.
Multi-bit fields
Some settings take several bits. Suppose bits 4 to 6 hold a 3-bit prescaler field with values 0 to 7. To read it, mask and shift down. To write it, clear the field, then OR in the new value shifted into place:
field_mask = 0x7u << 4 (0111 0000)
read: value = (reg & field_mask) >> 4
write: reg = (reg & ~field_mask) | ((new_value << 4) & field_mask)The final & field_mask stops an oversized new_value from spilling into neighbouring bits.
Reading a register map
Datasheets describe each register with a bit-by-bit map. Here is a made-up control register for a fictional timer, written the way datasheets usually present them:
TIMER_CTRL (8 bits, read/write, value after reset: 0x00)
bit 7 reserved always write 0
bits 6..4 PRESCALE clock divider select, 0 to 7
bit 3..2 reserved always write 0
bit 1 IRQ_EN 1 = interrupt on overflow
bit 0 EN 1 = timer runningFrom this, the code names follow naturally. Using named constants rather than raw numbers like 0x53 makes code readable and much easier to check against the datasheet.
#include <stdio.h>
#include <stdint.h>
#define CTRL_EN (1u << 0)
#define CTRL_IRQ_EN (1u << 1)
#define CTRL_PRESCALE_SHIFT 4
#define CTRL_PRESCALE_MASK (0x7u << CTRL_PRESCALE_SHIFT)
int main(void) {
uint8_t ctrl = 0x00; /* a plain variable standing in for the register */
ctrl |= CTRL_EN; /* set bit 0 */
printf("enable: 0x%02X\n", (unsigned)ctrl);
ctrl |= CTRL_IRQ_EN; /* set bit 1 */
printf("irq on: 0x%02X\n", (unsigned)ctrl);
/* write 5 into the 3-bit PRESCALE field, leaving other bits alone */
ctrl = (ctrl & ~CTRL_PRESCALE_MASK)
| ((5u << CTRL_PRESCALE_SHIFT) & CTRL_PRESCALE_MASK);
printf("prescale=5: 0x%02X\n", (unsigned)ctrl);
ctrl &= ~CTRL_IRQ_EN; /* clear bit 1 */
printf("irq off: 0x%02X\n", (unsigned)ctrl);
ctrl ^= CTRL_EN; /* toggle bit 0 */
printf("toggle en: 0x%02X\n", (unsigned)ctrl);
unsigned prescale = (ctrl & CTRL_PRESCALE_MASK) >> CTRL_PRESCALE_SHIFT;
printf("prescale field reads %u, enabled: %s\n", prescale,
(ctrl & CTRL_EN) ? "yes" : "no");
return 0;
}This is portable C: it runs on any computer, using a variable in place of the hardware. Output:
enable: 0x01
irq on: 0x03
prescale=5: 0x53
irq off: 0x51
toggle en: 0x50
prescale field reads 5, enabled: noCheck 0x53 by hand: in binary it is 0101 0011. Bits 6 to 4 are 101, which is 5; bit 1 and bit 0 are both 1. Exactly what we asked for.
From a variable to real hardware
On a real chip, the register lives at a fixed memory address given in the datasheet. Firmware reaches it through a pointer marked volatile, so the compiler performs every read and write exactly as written:
/* Illustrative pattern only. TIMER_CTRL_ADDRESS must come from your chip's
datasheet or the manufacturer's header file; no real address is shown here. */
#define TIMER_CTRL (*(volatile uint8_t *)TIMER_CTRL_ADDRESS)
void timer_enable(void) {
TIMER_CTRL |= CTRL_EN; /* read the register, set bit 0, write it back */
}In practice, manufacturers supply header files that define every register and bit name, so you rarely type an address yourself. But knowing what those definitions do lets you read them, check them against the datasheet and debug them.
Two cautions. First, some register bits behave unusually: a datasheet may say a status bit is cleared by writing 1, or that a register is read-only. A read-modify-write on such a register can have side effects, so read the description of every bit you touch. Second, a read-modify-write takes several instructions. If an interrupt handler modifies the same register in the middle, one change can be lost, the same problem as the shared-variable race in the interrupts lesson.
Project
Decode and encode a register by hand
Use the made-up TIMER_CTRL register from this lesson.
- Decode these values by hand, stating PRESCALE, IRQ_EN and EN for each: 0x00, 0x31, 0x72, 0x7F. Which one breaks the datasheet's "always write 0" rule for the reserved bits?
- Starting from 0x51, write the single C statement that sets PRESCALE to 2 without changing any other bit. What is the new value in hex?
- Extend the program in this lesson with a function
void set_prescale(uint8_t *reg, unsigned value)and test it with values 0, 7 and 9. What does your function do with 9, and is that what you want?
Check your hand answers by running the program.
Deliverables
- A decoded breakdown of the four values, with the rule-breaking value identified
- Your C statement and the resulting hex value
- The set_prescale function, its test output and a sentence on handling 9
Knowledge check
Check your understanding
Go further
- Bitwise operations in C (Wikipedia) ↗
Each operator with worked examples, and the difference from logical operators.
- Mask (computing) (Wikipedia) ↗
Common masking patterns for setting, clearing and testing bits.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.