Fixed-point math in C for MCUs without an FPU
Many small microcontrollers have no floating-point unit. Software floating point works, but it may cost flash and cycles depending on the operation and target. Fixed-point arithmetic represents fractions using integer instructions; measure latency and numerical error on the target.
The idea
Pick a scale factor that is a power of two. In Q15 format a 16-bit signed integer x represents the value x / 32768. The range is -1.0 to just under +1.0, and the smallest step is 1/32768, about 0.0000305. In Q16.16 a 32-bit integer represents x / 65536, giving a range of about -32768 to +32768 and a step of about 0.0000153.
Addition and subtraction need nothing special as long as both operands use the same format and you watch for overflow. Multiplication is where the care goes.
Multiplying Q15 numbers
The product of two Q15 numbers has 30 fractional bits, so you must shift right by 15 to get back to Q15. Do the multiply in a 32-bit type or the intermediate result overflows. Adding half a unit in the last place (1 << 14) before the shift rounds to nearest instead of truncating toward minus infinity.
There is one corner case: -1.0 times -1.0 would be +1.0, which Q15 cannot represent, so the result must be saturated to the maximum value.
#include <stdint.h>
#include <stdio.h>
typedef int16_t q15_t;
#define Q15_MAX ((q15_t)32767)
#define Q15_MIN ((q15_t)-32768)
static q15_t q15_from_double(double x)
{
double v = x * 32768.0;
if (v >= 32767.0) return Q15_MAX;
if (v <= -32768.0) return Q15_MIN;
return (q15_t)(v + (v >= 0 ? 0.5 : -0.5));
}
static q15_t q15_mul(q15_t a, q15_t b)
{
int32_t p = (int32_t)a * (int32_t)b; /* up to 2^30, fits in 32 bits */
p += (1 << 14); /* round to nearest */
p >>= 15; /* implementation-defined for negatives; arithmetic on GCC/Clang/ARM */
if (p > Q15_MAX) p = Q15_MAX; /* only (-1.0) * (-1.0) gets here */
return (q15_t)p;
}
static q15_t q15_add_sat(q15_t a, q15_t b)
{
int32_t s = (int32_t)a + (int32_t)b;
if (s > Q15_MAX) s = Q15_MAX;
if (s < Q15_MIN) s = Q15_MIN;
return (q15_t)s;
}
int main(void)
{
q15_t half = q15_from_double(0.5), quarter = q15_from_double(0.25);
printf("0.5 = %d, 0.25 = %d\n", half, quarter);
printf("0.5 * 0.5 -> %d (expect %d)\n", q15_mul(half, half), quarter);
printf("-0.5 * 0.5 -> %d (expect %d)\n", q15_mul((q15_t)-half, half), -quarter);
printf("-1.0 * -1.0 -> %d (saturated to max)\n", q15_mul(Q15_MIN, Q15_MIN));
printf("0.75 + 0.75 -> %d (saturated to max)\n", q15_add_sat(q15_from_double(0.75), q15_from_double(0.75)));
/* maximum multiply error over a grid of operand pairs, in LSBs */
double worst = 0.0;
for (int a = -32768; a <= 32767; a += 257) {
for (int b = -32768; b <= 32767; b += 263) {
double exact = (double)a * (double)b / 32768.0;
if (exact > 32767.0) exact = 32767.0; /* saturated corner */
double err = (double)q15_mul((q15_t)a, (q15_t)b) - exact;
if (err < 0) err = -err;
if (err > worst) worst = err;
}
}
printf("max error over grid: %.3f LSB (rounding guarantees <= 0.5)\n", worst);
if (worst > 0.5 + 1e-9) return 1;
return (q15_mul(half, half) == quarter) ? 0 : 1;
}
0.5 = 16384, 0.25 = 8192 0.5 * 0.5 -> 8192 (expect 8192) -0.5 * 0.5 -> -8192 (expect -8192) -1.0 * -1.0 -> 32767 (saturated to max) 0.75 + 0.75 -> 32767 (saturated to max) max error over grid: 0.500 LSB (rounding guarantees <= 0.5)
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
A note on right shifts of negative numbers
In ISO C, right-shifting a negative signed value is implementation-defined, not undefined. GCC, Clang and the ARM toolchains all implement it as an arithmetic shift (the sign bit is copied in), and most fixed-point libraries depend on that. If you need strict portability, say so in your coding standard, or divide by a power of two instead and accept the rounding difference.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
When to choose which format
| Format | Range | Step | Typical use |
|---|---|---|---|
| Q15 (16-bit) | -1 to +1 | 0.0000305 | audio, filters, normalized sensor data |
| Q1.31 (32-bit) | -1 to +1 | 0.00000000047 | high-precision filter state |
| Q16.16 (32-bit) | about +/-32768 | 0.0000153 | control loops, PID gains, scaling |
Mistakes to avoid
- Multiplying two
int16_twithout casting first. The promotion happens toint, which is 32 bits on ARM, but on a 16-bit targetintis 16 bits and you overflow. - Mixing formats in one expression without shifting.
- Forgetting saturation on accumulators in filters. A wrapped accumulator is a loud click in audio or a runaway in a control loop.
- Truncating instead of rounding in a long chain. The bias adds up.
Once you are comfortable with this, bit-level helpers like counting trailing zeros are the next tools worth knowing, for example when you normalize a value before dividing.
Convert familiar fractions to Q15
A Q15 integer stores the real number multiplied by 32768. For example, 0.5 becomes 16384 and 0.25 becomes 8192. Multiply the stored integers in a wide type to obtain 134217728, then divide by 32768 to return to the Q15 scale: 4096 represents 0.125. The scale is part of the type's interpretation, not an extra bit in memory.
| Real number | Stored Q15 integer |
|---|---|
| -1.0 | -32768 |
| 0.0 | 0 |
| 0.25 | 8192 |
| 0.5 | 16384 |
| 1.0 (saturated) | 32767 |
Interview check: why widen before multiplying?
The product has twice as many fractional bits as either input, so a narrow intermediate can lose information even if the final value fits. A wider intermediate preserves the product before rescaling. Specify tie behavior for negative values and define whether overflow saturates or is reported. Fixed-point performance depends on compiler and processor: benchmark the real target rather than assuming it always wins. For signed rounding details see fixed-point rounding in C.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.