---
title: Fixed-point arithmetic
heading: Fractions on a processor with no floating point
eyebrow: C12 · Lesson 18 · Fixed-point arithmetic
xp: 40
---

::: hook
This board's processor, like most small microcontrollers, has no floating-point hardware. A C compiler can still do `float` arithmetic in software, hundreds of instructions per operation, and many embedded compilers and code reviews forbid it for that reason (this course's compiler doesn't offer it at all). The alternative is **fixed point**: keep every quantity as an integer in small units, millivolts or tenths of a degree, or as an integer scaled by a power of two, and do everything with integer multiplies, divides and shifts. It's fast and exact to a known resolution, as long as you watch two things: rounding, and overflow.
:::

::: play
- The program reads the thermistor and prints three integers: the raw code, the voltage in millivolts, and the temperature in tenths of a degree, all without floating point.
- The temperature comes from a table of codes at 0, 10, ..., 80 °C, with straight-line interpolation between entries. Move the temperature slider and compare the printed tenths with it.
- At 5 °C the table gives 48 (4.8 °C): straight lines between points 10 °C apart miss the curve slightly. A table every 5 °C would halve that error, or better.
:::
:::

```sim board
lang: c
attach: thermistor ADC1 | temp 25
run: 10 ms
show: debug
code:
#include "board.h"

// ADC codes at 0, 10, 20, ... 80 °C for this thermistor and divider
const uint16_t table[9] = {939, 1357, 1817, 2270, 2676, 3014, 3280, 3482, 3633};

int read_adc(int ch) {
    ADC_CTRL = ch | ADC_START;
    while (!(ADC_STATUS & ADC_DONE)) ;
    ADC_STATUS = ADC_DONE;
    return ADC_DATA;
}

// Temperature in tenths of a degree, interpolating in the table.
int tenths(int code) {
    if (code <= table[0]) return 0;
    for (int i = 0; i < 8; i++)
        if (code <= table[i + 1])
            return i * 100 + (code - table[i]) * 100 / (table[i + 1] - table[i]);
    return 800;
}

int main(void) {
    int code = read_adc(1);
    int mv = (code * 3300 + 2047) / 4095;   // millivolts, rounded
    print(code);
    print(mv);
    print(tenths(code));
    return 0;
}
```

::: predict
## In C, `int mv = code * 3300 / 4095;` for code = 2048. Does it give the exact answer, 1650.4, rounded or truncated?

- [ ] Rounded: 1650
- [x] Truncated: 1650, but it would give 1650 for 1650.9 too
- [ ] 1650.4
- [ ] 0, because 3300/4095 is less than 1

::: reveal
Integer division truncates toward zero: $6\,758\,400/4095 = 1650.4$ becomes 1650, and 1650.9 would also become 1650. Adding half the divisor first, `(code * 3300 + 2047) / 4095`, rounds to the nearest instead. The order matters too: `code * (3300 / 4095)` would compute $3300/4095 = 0$ first.
:::
:::

::: nameit
## Scaled integers

Pick a unit small enough for the resolution you need and store whole numbers of it: millivolts, tenths of a degree, microseconds. Then

- multiply before dividing, to keep precision: `x * 3300 / 4095`, never `x * (3300 / 4095)`;
- round a division by adding half the divisor: `(a + b/2) / b` for positive values;
- check the largest intermediate value fits: here $4095 \times 3300 = 13.5 \times 10^6$, well under $2^{31} = 2.1 \times 10^9$.

## Binary fixed point (Q format)

A **Q16.16** number stores $x \times 2^{16}$ in 32 bits: 16 bits of integer and 16 of fraction, resolution $2^{-16} \approx 1.5 \times 10^{-5}$. Adding and subtracting work directly. Multiplying two Q16.16 values gives a Q32.32 product, which is shifted back right by 16 (and needs 64 bits in between unless the values are small). Shifts are cheap, so binary scaling is common in signal processing; decimal scaling is common for quantities people read.

## Tables and interpolation

Functions like logarithms and the thermistor's curve are expensive to compute, so firmware stores a table of values and interpolates linearly between neighbors:

$$y = y_i + (x - x_i)\frac{y_{i+1} - y_i}{x_{i+1} - x_i}$$

The error depends on the table's spacing and the curve's bend; halving the spacing cuts it about fourfold.
:::

::: example
## The ADC reads 2561. What temperature does the play's table give?

::: solution
1. **Find the table entries around it.** 2561 lies between 2270 (30 °C) and 2676 (40 °C).
2. **Interpolate in tenths of a degree.** The division is an integer one, so it drops the fraction:
   $$\begin{aligned} T &= 300 + \frac{(2561 - 2270) \times 100}{2676 - 2270} \\ &= 300 + \frac{29\,100}{406} \\ &= 300 + 71 \\ &= 371 \end{aligned}$$
   so 37.1 °C.
3. **Compare with the truth.** The true temperature for that code is 37.0 °C.

**Answer:** the table gives 37.1 °C.
:::
:::

::: example
## Multiply 1.5 by 2.25 in Q16.16.

::: solution
1. **Scale each number by $2^{16}$.**
   $$\begin{aligned} 1.5 \times 2^{16} &= 98\,304 \\ 2.25 \times 2^{16} &= 147\,456 \end{aligned}$$
2. **Multiply.** The product needs more than 32 bits:
   $$98\,304 \times 147\,456 = 1.4496 \times 10^{10}$$
3. **Shift right by 16.**
   $$221\,184 = 3.375 \times 2^{16}$$

**Answer:** 3.375, exactly.
:::
:::

::: example
## Store −1.75 in Q8.8 (16 bits, 8 fraction bits).

::: solution
1. **Scale by 256.**
   $$-1.75 \times 256 = -448$$
2. **Write it in 16-bit two's complement.**
   $$\begin{aligned} 65\,536 - 448 &= 65\,088 \\ &= \text{0xFE40} \end{aligned}$$
3. **Read it back.** Shifting right by 8 with sign gives −2 (rounded toward −∞), and the low byte 0x40 is the fraction:
   $$-2 + \frac{64}{256} = -1.75$$

**Answer:** −1.75 is stored as 0xFE40.
:::
:::

::: check
given: x = 0.5 | 1.25 | 3.142 | -2.75; n = 8 | 16
answer: round(x*2^n)
tolerance: 0

## What integer represents {x} in a Q format with {n} fraction bits?

::: right
Right. $\text{round}(x \cdot 2^n)$ = {answer}.
:::

::: misses
- [round(x*10^n)] Q formats scale by powers of two, not ten.
- [any] Not yet. Multiply by $2^n$ and round.
:::
:::

::: check
given: a = 1.5 | 0.75 | 3; b = 2 | 0.5 | 1.25; n = 8 | 16
answer: round(a*2^n)*round(b*2^n)/2^n
tolerance: 0

## In Q format with {n} fraction bits, {a} and {b} are stored as integers. What's their product, shifted back right by {n}, as an integer?

::: right
Right. {answer}, which is {a} × {b} in the same format.
:::

::: misses
- [any] Not yet. Multiply the integers, then shift right {n}.
:::
:::

::: check
given: c = 485 | 1484 | 2520 | 3704
answer: floor((c*3300 + 2047)/4095)
unit: mV
tolerance: 0

## The ADC reads {c}. What does `(c * 3300 + 2047) / 4095` give, in integer arithmetic?

::: right
Right. {answer} mV, rounded to the nearest millivolt.
:::

::: misses
- [floor(c*3300/4095)] Adding 2047 (half of 4095) first rounds instead of truncating.
- [any] Not yet. Integer division drops the fraction.
:::
:::

::: check
given: x = 1500 | 2000 | 2400; x0 = 1357; x1 = 2676; y0 = 100; y1 = 400
answer: y0 + floor((x - x0)*(y1 - y0)/(x1 - x0))
tolerance: 0

## Interpolate in integers: the table says {x0} → {y0} and {x1} → {y1}. What does {x} give, truncated?

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

::: misses
- [any] Not yet. $y_0 + (x - x_0)(y_1 - y_0)/(x_1 - x_0)$, multiplying before dividing.
:::
:::

::: check
given: a = 4095; b = 3300 | 100000 | 1000000
answer: a*b
tolerance: 0.5%

## A computation multiplies a 12-bit code (up to {a}) by {b} before dividing. What's the largest intermediate value? (A signed 32-bit int holds up to about 2.1 × 10⁹.)

::: right
Right. {answer}: compare it with $2^{31}$.
:::

::: misses
- [any] Not yet. The largest code times {b}.
:::
:::

::: check
kind: choice

## Which line computes millivolts from a 12-bit code most accurately in integer C?

- [ ] `mv = code * (3300 / 4095);`
- [ ] `mv = code / 4095 * 3300;`
- [x] `mv = (code * 3300 + 2047) / 4095;`
- [ ] `mv = code * 3300 / 4096;`

::: misses
- [1] `3300 / 4095` is 0 in integer arithmetic.
- [2] `code / 4095` is 0 for every code below 4095.
- [4] This ADC's full scale is 4095 codes for 3.3 V, so it's 0.02% low; and it truncates.
:::
:::

::: check
kind: c
given: V = 1.2 | 2.05 | 2.6 | 3
attach: pot ADC0 = {V} V
run: 0.01
expect: print = round(V/3.3*4095), floor((round(V/3.3*4095)*3300 + 2047)/4095)

## Read the potentiometer on ADC0. Print the raw code, then the voltage in millivolts rounded to the nearest whole millivolt, using only integer arithmetic.

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

int main(void) {
    ADC_CTRL = 0 | ADC_START;
    while (!(ADC_STATUS & ADC_DONE)) ;
    int code = ADC_DATA;
    print(code);
    print(code * 3300 / 4096);
    return 0;
}
```

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

int main(void) {
    ADC_CTRL = 0 | ADC_START;
    while (!(ADC_STATUS & ADC_DONE)) ;
    int code = ADC_DATA;
    print(code);
    print((code * 3300 + 2047) / 4095);
    return 0;
}
```

::: right
Right: full scale is 4095, and adding half the divisor rounds.
:::
:::

::: check
kind: c
given: X = 2300 | 2450 | 2600
run: 0.01
expect: print = 131, 300 + floor((X - 2270)*100/406)

## Write `int tenths(int code)` using the table from the play (codes at 0, 10, ... 80 °C), interpolating in integers. Print `tenths(1500)`, then `tenths(X)` for X = {X}.

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

int main(void) {
    print(1500);
    print(X);
    return 0;
}
```

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

const uint16_t table[9] = {939, 1357, 1817, 2270, 2676, 3014, 3280, 3482, 3633};

int tenths(int code) {
    if (code <= table[0]) return 0;
    for (int i = 0; i < 8; i++)
        if (code <= table[i + 1])
            return i * 100 + (code - table[i]) * 100 / (table[i + 1] - table[i]);
    return 800;
}

int main(void) {
    print(tenths(1500));
    print(tenths(X));
    return 0;
}
```

::: right
Right. Find the two entries the code lies between, then interpolate, multiplying before dividing.
:::
:::

::: check
kind: parts
given: a = 1.5 | -0.75 | 3.25; b = 2.25 | 0.5

## {a} and {b} are multiplied in Q16.16.

::: part
answer: round(a*65536)
tolerance: 0

### What integer stores {a}?

::: misses
- [any] $a \times 2^{16}$.
:::
:::

::: part
answer: floor(round(a*65536)*round(b*65536)/65536)
tolerance: 0

### What integer does the product, shifted right by 16, give?

::: misses
- [any] Multiply the integers (64 bits), shift right 16.
:::
:::
:::

::: check
kind: parts
given: x = -1.75 | -0.5 | 2.375; n = 8 | 12

## A Q-format number has {n} fraction bits, in 16 bits.

::: part
answer: round(x*2^n) + 65536*step(-x)
tolerance: 0

### What unsigned 16-bit pattern stores {x}?

::: misses
- [any] $x \cdot 2^n$, plus 65,536 if negative.
:::
:::

::: part
answer: 2^(15 - n)
tolerance: 0.5%

### What is the largest magnitude it can hold, about?

::: misses
- [any] $2^{15 - n}$.
:::
:::
:::

::: explain
## Why multiply before dividing in fixed-point arithmetic, and what's the risk?

::: model
Integer division discards the fraction, so dividing first throws away precision that later steps can never recover: `code / 4095 * 3300` is 0 for any code below 4095, and even a better ordering loses up to one unit at each division. Multiplying first keeps all the significant digits until the single division at the end, so only one rounding error happens. The risk is overflow: the intermediate product is much larger than the result, so it must fit the integer type, which means checking the largest possible inputs (4095 × 3300 is fine in 32 bits; 4095 × 10⁶ is not) and, if needed, using a wider type or scaling down first.
:::
:::

::: practice

::: check
given: x = 0.1 | 2.5; n = 8 | 15
answer: round(x*2^n)
tolerance: 0

## {x} with {n} fraction bits, as an integer?

::: misses
- [any] $\text{round}(x \cdot 2^n)$.
:::
:::

::: check
given: c = 100 | 333 | 1000 | 1234 | 2048 | 3000 | 4000
answer: floor((c*3300 + 2047)/4095)
unit: mV
tolerance: 0

## Rounded millivolts for code {c}?

::: misses
- [any] Add half the divisor.
:::
:::

::: check
given: a = 4095; b = 1000 | 10000 | 50000 | 100000 | 330000 | 600000
answer: a*b
tolerance: 0.5%

## Largest intermediate of a 12-bit code times {b}?

::: misses
- [any] 4095 × {b}.
:::
:::
:::
