The Engineering Desk
From the makers of RS-1

DesignSoftware Engineering

Fixed-point arithmetic on microcontrollers

Q formats, scaling and the overflow and rounding traps of integer math for fractional values.

Many small microcontrollers have no floating-point hardware. Software floating point works, but it can be ten to a hundred times slower than integer math. Fixed-point arithmetic stores fractional values in ordinary integers with an agreed scale factor. That gives predictable speed and exact, repeatable results.

The Q format

In Qm.n notation, a number has mm integer bits and nn fractional bits. The stored integer NN represents the real value:

x=N2nx = \frac{N}{2^{n}}

A common choice is Q15 in a 16-bit signed integer: one sign bit and 15 fractional bits, covering −1≤x<1-1 \le x < 1 with a resolution of 2−15≈3.05×10−52^{-15} \approx 3.05 \times 10^{-5}. Q16.16 in a 32-bit integer covers about ±32,768 with a resolution of about 1.5×10−51.5 \times 10^{-5}.

Basic operations

  • Addition and subtraction work directly when both values use the same Q format. Watch for overflow.
  • Multiplication doubles the number of fractional bits. Two Q15 values multiply into a Q30 result in 32 bits, which is shifted right by 15 to return to Q15:
    Nc=Na Nb215N_{c} = \frac{N_a\,N_b}{2^{15}}
  • Division works the other way: shift the dividend left by nn bits first, then divide.

Worked example

A 12-bit ADC reads a pressure sensor. The conversion to kPa is P=0.0610×counts−12.5P = 0.0610 \times \text{counts} - 12.5. In Q16.16, the gain is stored as 0.0610×65536≈39980.0610 \times 65536 \approx 3998 and the offset as −12.5×65536=−819200-12.5 \times 65536 = -819200. For a reading of 2048 counts:

NP=3998×2048−819200=7,368,704N_P = 3998 \times 2048 - 819200 = 7{,}368{,}704
P=7,368,70465536≈112.44 kPaP = \frac{7{,}368{,}704}{65536} \approx 112.44\ \text{kPa}

The floating-point answer is 112.43 kPa. The small difference comes from rounding the gain to an integer, and it's known in advance.

Illustrative sensor scaling.

Pitfalls

  • Overflow. Intermediate products need twice the width. Multiply two 32-bit values in a 64-bit accumulator.
  • Rounding. A plain right shift truncates toward negative infinity. Add half an LSB before shifting to round to nearest.
  • Saturation. In control loops, clamp results to the representable range rather than letting them wrap around from positive to negative.
  • Documentation. Name variables with their format, such as gain_q16, so the scale is never ambiguous.

More in Software Engineering