---
title: C for small machines
heading: Fixed-width types, bits, and volatile
eyebrow: C12 · Lesson 4 · C for small machines
xp: 40
---

::: hook
Three habits separate firmware C from C written for a desktop. Sizes are spelled out (`uint8_t`, `uint32_t`), because an `int` is 16 bits on some microcontrollers and 32 on others, and a register is exactly as wide as the datasheet says. Single bits are set, cleared and tested with masks, because one register packs many settings. And variables that hardware or an interrupt can change are marked `volatile`, because an optimizing compiler otherwise assumes nothing changes behind its back, and will happily turn a wait loop into a loop that waits forever.
:::

::: play
- A timer interrupt sets `done` after 10 ms; `main` waits for it, then lights the LED. As written, `done` isn't volatile. Run it: the LED never lights.
- Open the compiled program and find `main`'s wait: the compiler read `done` once, before the loop, and the loop jumps to itself. Nothing inside the loop could change `done`, as far as the compiler can see.
- Add `volatile` before `int done` and run again: now the loop reads `done` every time, and the LED lights at 10 ms.
:::
:::

```sim board
lang: c
attach: led P0 | green
scope: P0
run: 50 ms
show: asm
code:
#include "board.h"

int done = 0;            // set by the interrupt; try: volatile int done = 0;

void __attribute__((interrupt)) on_timer(void) {
    TIMER_FLAGS = 1;
    TIMER_CTRL = 0;      // one shot: stop the timer
    done = 1;
}

int main(void) {
    GPIO_DIR = 1;
    set_trap_handler(on_timer);
    TIMER_PRESCALE = 9;  // 1 MHz ticks
    TIMER_TOP = 9999;    // 10 ms
    TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
    enable_external_interrupt();
    enable_interrupts();
    while (!done)        // wait for the interrupt
        ;
    GPIO_SET = 1;        // then light the LED
    while (1) ;
}
```

::: predict
## A `uint8_t count` holds 250. After `count = count + 10;`, what does it hold?

- [ ] 260
- [x] 4
- [ ] 255
- [ ] It's undefined

::: reveal
4. The addition happens in `int` (C promotes small types first), giving 260, but storing it back into 8 bits keeps only the low 8: $260 - 256 = 4$. Unsigned types wrap like this by definition; signed overflow, by contrast, is undefined in C, which is one more reason firmware uses unsigned types for counters and registers.
:::
:::

::: nameit
## Fixed-width types

| Type (`<stdint.h>`) | Bits | Range |
|---|---|---|
| `uint8_t`, `int8_t` | 8 | 0 to 255; −128 to 127 |
| `uint16_t`, `int16_t` | 16 | 0 to 65,535; −32,768 to 32,767 |
| `uint32_t`, `int32_t` | 32 | 0 to 4,294,967,295; about ±2.1 × 10⁹ |

Arithmetic on anything narrower than `int` happens in `int` and is truncated when stored. Unsigned arithmetic wraps modulo $2^n$; signed overflow is undefined. On this board `char` is unsigned, as the RISC-V convention says.

## Bit operations

| Goal | C |
|---|---|
| set bit n | `x \|= 1u << n` |
| clear bit n | `x &= ~(1u << n)` |
| flip bit n | `x ^= 1u << n` |
| test bit n | `if (x & (1u << n))` |
| read a w-bit field at bit s | `(x >> s) & ((1u << w) - 1)` |
| write field value v | `x = (x & ~(((1u << w) - 1) << s)) \| (v << s)` |

## volatile

`volatile` says a variable can change, or its accesses matter, outside the program's normal flow. The compiler must then load it every time it's read and store it every time it's written. Use it for:

- memory-mapped registers (the header's definitions already include it);
- variables shared between an interrupt handler and the main program;
- a delay loop's counter, so the loop isn't removed.

It doesn't make an access atomic: a 32-bit increment is still a load, an add and a store, and an interrupt can land between them (lesson 12).
:::

::: example
## A status register holds 0x0000_3A54. Bits 4 to 7 are a "mode" field. What mode is it in?

::: solution
1. **Shift the field down.** Shifting right by 4 moves bit 4 to bit 0:
   $$\text{0x3A54} \gg 4 = \text{0x3A5}$$
2. **Mask off the other bits.**
   $$\text{0x3A5}\ \&\ \text{0xF} = \text{0x5}$$

**Answer:** it is in mode 5.
:::
:::

::: example
## Write mode 0xC into the same field and leave every other bit alone.

::: solution
1. **Build the mask.**
   $$\sim(\text{0xF} \ll 4) = \text{0xFFFF\_FF0F}$$
2. **Clear the field.**
   $$\begin{aligned} &\text{0x3A54}\ \&\ \text{0xFFFF\_FF0F} \\ &= \text{0x3A04} \end{aligned}$$
3. **OR in the new value.**
   $$\begin{aligned} &\text{0x3A04}\ |\ (\text{0xC} \ll 4) \\ &= \text{0x3A04}\ |\ \text{0xC0} \\ &= \text{0x3AC4} \end{aligned}$$

**Answer:** the register becomes 0x3AC4.
:::
:::

::: example
## What do 200 + 100 give in a `uint8_t`, and 100 + 100 in an `int8_t`?

::: solution
1. **The `uint8_t` sum.** It wraps modulo 256:
   $$300 - 256 = 44$$
2. **The `int8_t` sum.** An `int8_t` holds −128 to 127, and 200 doesn't fit; on this machine it wraps to
   $$200 - 256 = -56$$
3. **Which overflow is defined.** Unsigned overflow is defined behavior in C; signed overflow isn't, which is why counters and checksums use unsigned types.

**Answer:** 44 in a `uint8_t`, and −56 in an `int8_t` on this machine.
:::
:::

::: check
given: x = 0x3A54 | 0xBEEF | 0x12F0 | 0xC0DE; s = 4 | 8; w = 4
base: 16
answer: floor(x/2^s) - 2^w*floor(x/2^(s + w))

## Read the {w}-bit field at bit {s} of {x:hex4}. What value is it, in hex?

::: right
Right. `(x >> {s}) & 0xF` = {answer:hex1}.
:::

::: misses
- [any] Not yet. Shift right by {s}, then keep the low {w} bits.
:::
:::

::: check
given: x = 0x89 | 0xB9 | 0xFF; n = 0 | 3 | 7
base: 16
answer: x - (floor(x/2^n) - 2*floor(x/2^(n + 1)))*2^n

## A register byte holds {x:hex2}. What does it hold after `x &= ~(1u << {n});`, in hex?

::: right
Right. {answer:hex2}: bit {n} cleared, every other bit kept.
:::

::: misses
- [x] Bit {n} was 1 there, and clearing makes it 0.
- [any] Not yet. Clear only bit {n}.
:::
:::

::: check
given: a = 200 | 250 | 255; b = 60 | 100 | 120
answer: a + b - 256*floor((a + b)/256)

## A `uint8_t` holds {a}. What does it hold after adding {b}?

::: right
Right. {answer}: the sum modulo 256.
:::

::: misses
- [a + b] It's 8 bits wide: only the low 8 bits of the sum are kept.
- [255] Unsigned values wrap around; they don't stop at the top.
- [any] Not yet. $(a + b) \bmod 256$.
:::
:::

::: check
given: n = 10 | 64 | 100; s = 1 | 2 | 4
answer: n*s
unit: bytes
tolerance: 0

## An array of {n} elements, each {s} byte(s) wide (`uint8_t`, `uint16_t` or `uint32_t`): how many bytes of RAM does it use?

::: right
Right. {answer} bytes.
:::

::: misses
- [any] Not yet. Elements times bytes each.
:::
:::

::: check
given: w = 3 | 5 | 8 | 12
answer: 2^w - 1
tolerance: 0

## What's the largest value a {w}-bit unsigned field can hold?

::: right
Right. $2^{\given{w}} - 1$ = {answer}.
:::

::: misses
- [2^w] Counting starts at 0, so the top is one less.
- [any] Not yet. $2^w - 1$.
:::
:::

::: check
kind: choice

## Which variable needs `volatile`?

- [ ] A loop counter used only inside one function
- [x] A flag that an interrupt handler sets and `main` waits on
- [ ] A constant table of sine values
- [ ] A function's return value

::: misses
- [1] The compiler sees every change to it.
- [3] It never changes, so caching it is fine; it can be `const`.
- [4] Return values are ordinary values.
:::
:::

::: check
kind: c
attach: led P0
run: 0.05
expect: level(P0) = 1; first(P0) = 10 ms ± 1%

## This program waits for a timer interrupt and then lights the LED, but the LED never lights. Fix it.

```c starter
#include "board.h"

int done = 0;

void __attribute__((interrupt)) on_timer(void) {
    TIMER_FLAGS = 1;
    TIMER_CTRL = 0;
    done = 1;
}

int main(void) {
    GPIO_DIR = 1;
    set_trap_handler(on_timer);
    TIMER_PRESCALE = 9;
    TIMER_TOP = 9999;
    TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
    enable_external_interrupt();
    enable_interrupts();
    while (!done)
        ;
    GPIO_SET = 1;
    while (1) ;
}
```

```c solution
#include "board.h"

volatile int done = 0;

void __attribute__((interrupt)) on_timer(void) {
    TIMER_FLAGS = 1;
    TIMER_CTRL = 0;
    done = 1;
}

int main(void) {
    GPIO_DIR = 1;
    set_trap_handler(on_timer);
    TIMER_PRESCALE = 9;
    TIMER_TOP = 9999;
    TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
    enable_external_interrupt();
    enable_interrupts();
    while (!done)
        ;
    GPIO_SET = 1;
    while (1) ;
}
```

::: right
Right. With `volatile`, every pass of the wait loop reads `done` from memory, so it sees the interrupt's write.
:::
:::

::: check
kind: c
given: X = 23130 | 48879 | 4848 | 49374; S = 4 | 8
run: 0.01
expect: print = floor(X/2^S) - 16*floor(X/2^(S + 4)), X - (floor(X/2^S) - 16*floor(X/2^(S + 4)))*2^S + 12*2^S

## `X` is {X}. Print the 4-bit field that starts at bit `S` ({S}), then print X with that field replaced by 12 and every other bit unchanged.

```c starter
#include "board.h"

int main(void) {
    uint32_t v = X;
    print(v);
    return 0;
}
```

```c solution
#include "board.h"

int main(void) {
    uint32_t v = X;
    uint32_t field = (v >> S) & 0xF;
    print(field);
    v = (v & ~(0xFu << S)) | (12u << S);
    print(v);
    return 0;
}
```

::: right
Right. Shift and mask to read; clear with an inverted mask and OR to write.
:::
:::

::: check
kind: parts
given: v = 14932 | 3735 | 61455; p = 4 | 8; w = 3 | 4

## A register holds {v:hex4}. A field of {w} bits starts at bit {p}.

::: part
answer: floor(v/2^p) - 2^w*floor(v/2^(p + w))
tolerance: 0

### What is the field's value?

::: misses
- [any] Shift right by {p}, mask {w} bits.
:::
:::

::: part
answer: v - 2^p*(floor(v/2^p) - 2^w*floor(v/2^(p + w)))
tolerance: 0
base: 16
width: 4

### What does the register hold after the field is cleared?

::: misses
- [any] AND with the inverted mask.
:::
:::
:::

::: check
kind: parts
given: a = 120 | 200 | 250; b = 100 | 150

## {a} and {b} are added in 8-bit variables.

::: part
answer: a + b - 256*floor((a + b)/256)
tolerance: 0

### What does a `uint8_t` hold?

::: misses
- [any] The sum modulo 256.
:::
:::

::: part
answer: a + b - 256*floor((a + b)/256) - 256*step(a + b - 256*floor((a + b)/256) - 127.5)
tolerance: 0

### What does the same bit pattern mean as an `int8_t`?

::: misses
- [any] Patterns of 128 and above are negative: subtract 256.
:::
:::
:::

::: explain
## Why can an optimizing compiler turn `while (!done) ;` into an endless loop when `done` isn't volatile?

::: model
The compiler reasons only about the code it can see. Inside the loop nothing writes to `done` and nothing calls a function that might, so as far as the C language is concerned `done` can't change while the loop runs. It's therefore free to load `done` once before the loop and test the copy in a register on every pass, or to decide the loop either exits immediately or never exits. An interrupt handler changes `done` from outside that view, so the cached copy never updates. Declaring `done` volatile tells the compiler the value can change at any moment, which forces a fresh load from memory on every pass.
:::
:::

::: practice

::: check
given: x = 0xA5 | 0x3C; n = 2 | 6
base: 16
answer: x - (floor(x/2^n) - 2*floor(x/2^(n + 1)))*2^n

## {x:hex2} after clearing bit {n}, in hex?

::: misses
- [any] Clear only bit {n}.
:::
:::

::: check
given: a = 240 | 255; b = 20 | 30
answer: a + b - 256*floor((a + b)/256)

## `uint8_t` {a} plus {b}?

::: misses
- [any] Modulo 256.
:::
:::

::: check
given: w = 3..16 int
answer: 2^w - 1
tolerance: 0

## Largest value in {w} unsigned bits?

::: misses
- [any] $2^w - 1$.
:::
:::
:::
