---
title: Multiplication, division and fixed point
heading: Arithmetic with whole numbers that stands in for fractions
eyebrow: C8 · Lesson 20 · Multiplication, division and fixed point
xp: 40
---

::: hook
A sensor reading arrives as a 12-bit number from 0 to 4095, and the display needs millivolts. A digital filter needs to multiply each sample by 0.7. Many small processors have no floating-point hardware, and the ones that do often avoid it in interrupt handlers, so this arithmetic is done with integers: multiply, then shift. RISC-V's M extension adds the multiply and divide instructions, and using them well means knowing how wide a product gets, which way division rounds, and how to keep track of a binary point that the hardware knows nothing about.
:::

::: play
- The program scales a 12-bit ADC reading to millivolts, multiplies 0.5 by 0.75 in a 16-bit fraction format, and divides −7 by 2 two different ways.
- Step it. a1 ends at 2199 mV: 2730 × 3300 / 4096 with the fraction dropped. a2 ends at 12288, which is 0.375 × 32768.
- Compare a3 and a5: `div` gives −3, rounding toward zero, while shifting right by one gives −4, rounding down.
:::
:::

```sim cpu
.text
    li a0, 2730          # a 12-bit ADC reading
    li t0, 3300          # the reference, in millivolts
    mul a1, a0, t0       # code x 3300
    srli a1, a1, 12      # divide by 4096: millivolts
    li t1, 16384         # 0.5 as a Q15 number
    li t2, 24576         # 0.75 as a Q15 number
    mul a2, t1, t2       # the product has 30 fraction bits
    srai a2, a2, 15      # back to 15: 12288, which is 0.375
    li t3, -7
    li t4, 2
    div a3, t3, t4       # rounds toward zero
    rem a4, t3, t4       # the remainder takes the dividend's sign
    srai a5, t3, 1       # a shift rounds down
    ebreak
show: a0, a1, a2, a3, a4, a5
speed: 3
```

::: predict
## Two 32-bit numbers are multiplied. How many bits can the full product need?

- [ ] 32
- [ ] 33
- [x] 64
- [ ] 1024

::: reveal
64. An n-bit number times an m-bit number needs up to n + m bits. `mul` keeps the low 32 bits of the product; `mulh` (signed) and `mulhu` (unsigned) return the high 32, so a pair of instructions gets the whole thing.
:::
:::

::: nameit
## Multiply and divide

| Instruction | Result |
|---|---|
| `mul rd, a, b` | the low 32 bits of a × b (the same for signed and unsigned) |
| `mulh`, `mulhu`, `mulhsu` | the high 32 bits, for signed × signed, unsigned × unsigned, signed × unsigned |
| `div`, `divu` | the quotient, rounded toward zero |
| `rem`, `remu` | the remainder, with the sign of the dividend |

so that $a = b \cdot \text{div}(a, b) + \text{rem}(a, b)$ always holds: −7 = 2 × (−3) + (−1). Division by zero doesn't trap: the quotient is all ones and the remainder is the dividend, and the program has to check for zero itself if it matters. Dividing is slow on most processors (often 10 to 40 cycles against one for a multiply), so compilers turn division by a constant into a multiply and a shift.

**Shifting instead.** `srai x, x, k` divides by $2^k$ rounding down (toward −∞), so for negative numbers it differs from `div` whenever there's a remainder. `slli` multiplies by $2^k$.

## Fixed point

A **fixed-point** number is an integer with an agreed binary point. In **Qm.n** format there are n fraction bits, and the stored integer k means

$$x = \frac{k}{2^n}$$

The common **Q15** format packs a signed fraction into 16 bits: $k = \text{round}(x \cdot 2^{15})$, covering −1 to $1 - 2^{-15}$ in steps of $2^{-15} \approx 3.05 \times 10^{-5}$.

- **Adding** two numbers with the same n is plain integer addition.
- **Multiplying** adds the fraction bits: Q15 × Q15 has 30 fraction bits, so shift right by 15 to get back to Q15. The 16-bit inputs make a product that fits easily in 32 bits.
- **Rounding:** adding $2^{k-1}$ before shifting right by k rounds to nearest instead of down.

## Scaling a reading

An N-bit converter with reference $V_\text{ref}$ maps code c to $c \cdot V_\text{ref}/2^N$. In millivolts that's one multiply and one shift, as long as $c \cdot V_\text{ref}$ fits in 32 bits.
:::

::: example
## Represent 0.7 in Q15 and multiply it by 0.5.

::: solution
1. **Represent 0.7.**
   $$0.7 \times 32768 = 22937.6$$
   which rounds to 22938.
2. **Represent 0.5.** 0.5 is 16384.
3. **Multiply.** The product has 30 fraction bits:
   $$22938 \times 16384 = 375{,}816{,}192$$
4. **Shift back to Q15.** Shifting right by 15 gives 11469:
   $$\frac{11469}{32768} = 0.350006$$
5. **The error.** The 6 millionths come from rounding 0.7.

**Answer:** 0.7 is 22938 in Q15, and the product is 11469, which is 0.350006.
:::
:::

::: example
## A 12-bit ADC with a 3.3 V reference reads 2730. Convert it to millivolts with integer arithmetic.

::: solution
1. **Multiply first.**
   $$2730 \times 3300 = 9{,}009{,}000$$
   which fits in 32 bits easily (the largest possible, $4095 \times 3300$, is about 13.5 million).
2. **Divide by 4096.** Shifting right by 12 divides by 4096: 2199 mV.
3. **Check.** The exact value is 2199.46 mV, so dropping the fraction costs less than one millivolt.

**Answer:** 2199 mV.
:::
:::

::: example
## Divide a 16-bit unsigned x by 10 without a divide instruction.

::: solution
1. **Scale the reciprocal.**
   $$\frac{2^{19}}{10} = 52428.8$$
   rounded up to 52429 (0xCCCD).
2. **Multiply and shift.**
   $$\frac{x}{10} \approx (x \times 52429) \gg 19$$
3. **Try x = 1234.** The product is 64,697,386, and shifting by 19 gives 123.
4. **Check the error.** The rounding error is $0.2/2^{19}$ per unit of x, too small to change any result for $x < 2^{16}$; a check over all 65,536 values confirms it.
5. **Where it's used.** Compilers do exactly this for division by a constant, because a multiply takes a few cycles and a divide dozens.

**Answer:** multiply by 52429 and shift right by 19, which is exact for every 16-bit x; for 1234 it gives 123.
:::
:::

::: check
given: x = 0.1 | 0.25 | -0.3 | 0.7 | -0.45
answer: round(x*32768)
tolerance: 0

## What integer represents {x} in Q15?

::: right
Right. round({x} × 32768) = {answer}.
:::

::: misses
- [any] Not yet. Multiply by $2^{15}$ and round.
:::
:::

::: check
given: a = 8192 | 16384 | 22938; b = 6554 | 24576 | 29491
answer: floor(a*b/32768)
tolerance: 0

## Two Q15 numbers, {a} and {b}, are multiplied with `mul` and the product shifted right by 15 (rounding down). What integer results?

::: right
Right. The product has 30 fraction bits; the shift brings it back to 15.
:::

::: misses
- [a*b] That's the raw product, with 30 fraction bits. Shift it right by 15.
- [floor(a*b/65536)] Shift by the fraction bits of one input: 15.
- [any] Not yet. $\lfloor ab/2^{15} \rfloor$.
:::
:::

::: check
given: c = 100..4095 int; V = 2500 | 3300 | 5000
answer: floor(c*V/4096)
unit: mV
tolerance: 0

## A 12-bit ADC with a {V} mV reference reads {c}. What does `mul` by {V} followed by `srli` by 12 give, in millivolts?

::: right
Right. {c} × {V}/4096, rounded down: {answer} mV.
:::

::: misses
- [any] Not yet. Multiply, then divide by 4096 and drop the fraction.
:::
:::

::: check
given: a = -7 | -23 | -45 | -61; b = 2 | 4
answer: -floor(-a/b)
tolerance: 0

## What does `div` give for {a} ÷ {b}?

::: right
Right. RISC-V division rounds toward zero: {answer}.
:::

::: misses
- [floor(a/b)] That rounds down, as `srai` would. `div` rounds toward zero.
- [any] Not yet. Divide and drop the fraction toward zero.
:::
:::

::: check
given: a = -7 | -23 | -45 | -61; b = 2 | 4
answer: a + b*floor(-a/b)
tolerance: 0

## What does `rem` give for {a} and {b}?

::: right
Right. The remainder takes the dividend's sign: {a} = {b} × (quotient) + ({answer}).
:::

::: misses
- [a - b*floor(a/b)] That's the always-positive modulus. `rem` matches `div`, which rounds toward zero.
- [any] Not yet. $a - b \cdot \text{div}(a, b)$.
:::
:::

::: check
kind: asm
given: p1 = 6..20 int; q1 = 6..20 int; p2 = -5..-1 int; q2 = 1..5 int; p3 = 1..20 int; q3 = 1..20 int
expect: a0 = p1*q1 + p2*q2 + p3*q3

## Compute the dot product of the three-word vectors `p` and `q` (the sum of p[i] × q[i]) and leave it in a0.

```asm starter
.data
p: .word p1, p2, p3
q: .word q1, q2, q3
.text
    la t0, p
    la t1, q
    ebreak
```

```asm solution
.data
p: .word p1, p2, p3
q: .word q1, q2, q3
.text
    la t0, p
    la t1, q
    li t2, 3
    li a0, 0
loop:
    beqz t2, done
    lw t3, 0(t0)
    lw t4, 0(t1)
    mul t3, t3, t4
    add a0, a0, t3
    addi t0, t0, 4
    addi t1, t1, 4
    addi t2, t2, -1
    j loop
done:
    ebreak
```

::: right
Right. A multiply-accumulate loop, the inner loop of every digital filter.
:::
:::

::: check
kind: asm
given: c = 1..4095 int
setup: a0 = c
expect: a1 = floor(c*3300/4096)

## a0 holds a 12-bit ADC code; the reference is 3300 mV. Put the reading in millivolts in a1, rounded down.

```asm starter
    # the code is in a0
    ebreak
```

```asm solution
    li t0, 3300
    mul a1, a0, t0
    srli a1, a1, 12
    ebreak
```

::: right
Right. One multiply and a shift; no division needed.
:::
:::

::: check
kind: choice

## Why do compilers replace `x / 8` for a signed int with more than a single `srai x, x, 3`?

- [ ] `srai` is slower than `div`
- [x] For negative x the shift rounds down, while C division rounds toward zero
- [ ] Shifts only work on unsigned numbers
- [ ] The shift loses the sign bit

::: misses
- [1] A shift is one of the fastest instructions there is; division is the slow one.
- [3] `srai` is the arithmetic shift, made for signed numbers.
- [4] `srai` copies the sign bit in from the left.
:::
:::

::: check
kind: parts
given: a = 0.3 | 0.45 | 0.8; b = 0.25 | 0.6 | -0.5

## Multiply {a} by {b} in Q15.

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

### What integer stores {a}?

::: misses
- [any] $a \times 2^{15}$, rounded.
:::
:::

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

### What Q15 integer does the product, shifted right 15, give?

::: misses
- [any] Multiply the integers and shift right by 15.
:::
:::
:::

::: check
kind: derivation
vars: x = -1..1, y = -1..1, n = 4..31

## A fixed-point number with n fraction bits stores the value x as the integer $X = x\,2^n$.

::: step
answer: x*2^n

### What integer stores x?
:::

::: step
answer: x*y*2^(2*n)

### What's the integer product XY?
:::

::: step
answer: x*y*2^n

### What is XY shifted right by n, the stored form of xy?
:::

::: right
Right. The product has 2n fraction bits; one shift restores n.
:::
:::

::: explain
## Why does multiplying two Q15 numbers need a shift afterward, while adding them doesn't?

::: model
A Q15 integer is the real value times $2^{15}$. Adding two of them gives $(x + y) \cdot 2^{15}$, which is already the Q15 form of the sum. Multiplying gives $x \cdot 2^{15} \cdot y \cdot 2^{15} = xy \cdot 2^{30}$: the scale factors multiply too, so the product has 30 fraction bits. Shifting right by 15 divides by $2^{15}$ and puts it back on the Q15 scale, throwing away the lowest 15 bits of precision, which is why rounding before the shift matters.
:::
:::

::: practice

::: check
given: n = 7 | 15 | 31
answer: 2^(-n)
tolerance: 0.1%

## What is the step between adjacent values of a Q-format number with {n} fraction bits?

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

::: check
given: k = 4096 | 8192 | -16384 | 24576
answer: k/32768
tolerance: 0.1%

## What value does the Q15 integer {k} represent?

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

::: check
given: n = 8 | 12 | 16; m = 10 | 20 | 24
answer: n + m
unit: bits
tolerance: 0

## How many bits can the product of an unsigned {n}-bit number and an unsigned {m}-bit number need?

::: misses
- [any] The widths add.
:::
:::
:::
