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 integer bits and fractional bits. The stored integer represents the real value:
A common choice is Q15 in a 16-bit signed integer: one sign bit and 15 fractional bits, covering with a resolution of . Q16.16 in a 32-bit integer covers about ±32,768 with a resolution of about .
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:
- Division works the other way: shift the dividend left by bits first, then divide.
Worked example
A 12-bit ADC reads a pressure sensor. The conversion to kPa is . In Q16.16, the gain is stored as and the offset as . For a reading of 2048 counts:
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.