Skip to content
systemcoding.dev
Embedded

The Complete Guide to Fixed-Point Arithmetic in Firmware

Learn fixed-point arithmetic for firmware in C: Q formats, conversion, multiply and divide, saturation, filters, printing and testing, with verified outputs.

27 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Arm, C and Raspberry Pi logos.

Many microcontrollers have no floating-point unit. A Cortex-M0+, an AVR, an MSP430 or a small RISC-V core does a floating-point addition by calling a library routine that takes dozens of cycles and adds kilobytes of code. Even on parts with an FPU, a program that must give identical results on every run, or that does heavy filtering at a high sample rate, often does better with integers. Fixed-point arithmetic is the technique of using integers to represent fractional numbers by agreeing, in your head and in your code, where the binary point sits. It is old, exact, fast and unforgiving: the compiler does not check your agreement, and every bug in it looks like a number that is plausible and wrong. This guide is the hub for the fixed-point posts on SystemCoding. It starts from the idea, then builds the operations one at a time, each with C code and the output the code produces, and ends with filters, printing, testing and the mistakes that cost the most time.

All code is C99 and assumes int may be 16 or 32 bits, so the examples use the fixed-width types from <stdint.h>. They compile with arm-none-eabi-gcc 14 or any C compiler, and the arithmetic does not depend on the target.

Nothing here was run on a board. Each program was written and its output worked out by reading it, and the numbers in the text can be checked by hand, which is part of the method: with fixed point you should always be able to predict the result.

The idea in one paragraph

An integer stores a count of units. If the unit is 1, the integer 5 means five. If you decide the unit is 1/256, the same stored bits mean 5/256, about 0.0195. You have chosen where the binary point sits: eight bits from the right. The processor still does integer arithmetic, and you interpret the results with the agreed scale. Addition and subtraction work unchanged, as long as both numbers use the same scale. Multiplication and division need a correction for the scale, which is a shift. Everything else in this guide is about doing those corrections without losing bits.

Q format: naming the agreement

Engineers write the agreement as Q notation. Qm.n means a signed number with m integer bits, n fractional bits, and one sign bit in addition, stored in m + n + 1 bits in total. Two conventions coexist. The ARM and CMSIS convention counts only the fractional bits and calls a 16-bit signed number with 15 fractional bits Q15, and a 32-bit one with 31 fractional bits Q31. The TI convention counts the sign bit as one of the integer bits, and writes Q1.15 for the same format. This guide uses the ARM style: Q15 means a 16-bit signed integer with 15 fractional bits, representing values from minus 1 up to a little below plus 1.

For a format with n fractional bits, the stored integer x represents the real value x / 2^n. The smallest step, the resolution, is 2^-n. The range is set by the word size.

FormatStored inReal rangeResolution
Q78 bits-1 to 0.99218750.0078125
Q1516 bits-1 to 0.9999694824218750.000030517578125
Q3132 bits-1 to 0.99999999953433874.656612873077393e-10
Q16.1632 bits-32768 to 32767.999980.0000152587890625
Q24.832 bits-8388608 to 8388607.9960.00390625

The first three are fractions only: they represent numbers between minus one and one, which suits normalized signals, filter coefficients and sine values. The last two mix an integer and a fractional part, which suits quantities with a range, such as a temperature or a position. Pick the split from the range of your data, not from habit.

The resolution row is arithmetic you can check. The step of Q15 is one over 32,768, and the largest rounding error when you convert a real number to Q15 is half a step:

qresolution.cc
#include <stdio.h>

int main(void)
{
    printf("Q15 step:       %.12f\n", 1.0 / 32768.0);
    printf("Q15 max error:  %.12f\n", 1.0 / 65536.0);
    printf("Q16.16 step:    %.12f\n", 1.0 / 65536.0);
    return 0;
}
Text
Q15 step:       0.000030517578
Q15 max error:  0.000015258789
Q16.16 step:    0.000015258789

Notice that Q15 is asymmetric. It reaches minus 1 exactly, as -32768, and cannot reach plus 1, whose nearest value is 32767, a hair below. That asymmetry creates the best-known fixed-point bug, which appears shortly.

Convert between real numbers and Q15

To convert a real number to Q15, scale by 32,768 and round to the nearest integer. Values outside the range must be clamped, or the conversion wraps around:

q15conv.cc
#include <stdint.h>
#include <stdio.h>
#include <math.h>

static int16_t float_to_q15(double x)
{
    double scaled = x * 32768.0;
    if (scaled >= 32767.0)
        return 32767;
    if (scaled <= -32768.0)
        return -32768;
    return (int16_t)lround(scaled);
}

static double q15_to_float(int16_t q)
{
    return q / 32768.0;
}

int main(void)
{
    double inputs[] = { 0.5, -0.25, 0.1, 1.0, -1.0, 1.5 };

    for (int i = 0; i < 6; i++) {
        int16_t q = float_to_q15(inputs[i]);
        printf("%5.2f -> %6d -> %.6f\n", inputs[i], q, q15_to_float(q));
    }
    return 0;
}
Text
 0.50 ->  16384 -> 0.500000
-0.25 ->  -8192 -> -0.250000
 0.10 ->   3277 -> 0.100006
 1.00 ->  32767 -> 0.999969
-1.00 -> -32768 -> -1.000000
 1.50 ->  32767 -> 0.999969

The value 0.5 is exactly 16,384, half of 32,768. The value 0.1 cannot be represented exactly: 0.1 times 32,768 is 3,276.8, which rounds to 3,277, and converting back gives 0.100006, an error of 6 millionths, well inside the half-step bound. The input 1.0 saturates to 32,767, and 1.5 does too. The dedicated post on float and Q15 conversion covers rounding modes and the macro form for compile-time constants.

The reverse conversion divides by 32,768, which on a core without an FPU you avoid by keeping everything in Q15 until the last moment, usually when printing.

Addition and subtraction: free, until they overflow

Two numbers in the same Q format add as integers. 0.5 + 0.25 in Q15 is 16384 + 8192 = 24576, which is 0.75. The danger is overflow: 0.75 + 0.5 is 1.25, which does not fit in Q15, and the 16-bit sum 24576 + 16384 = 40960 wraps to -24576, a large negative number. A wrapped result is far worse than a clipped one, since a slightly loud signal becomes a violent opposite-sign spike.

Saturating arithmetic clamps instead of wrapping. Some processors do this in one instruction: the ARM DSP extension on Cortex-M4 and M7 has QADD16, and CMSIS-DSP exposes the same behavior in arm_add_q15. In portable C, widen, add, clamp:

qadd.cc
#include <stdint.h>
#include <stdio.h>

static int16_t sat16(int32_t x)
{
    if (x > INT16_MAX) return INT16_MAX;
    if (x < INT16_MIN) return INT16_MIN;
    return (int16_t)x;
}

static int16_t q15_add_sat(int16_t a, int16_t b)
{
    return sat16((int32_t)a + (int32_t)b);
}

int main(void)
{
    int16_t a = 24576;    /* 0.75 */
    int16_t b = 16384;    /* 0.5 */

    printf("wrapped:   %d\n", (int16_t)(a + b));
    printf("saturated: %d\n", q15_add_sat(a, b));
    return 0;
}
Text
wrapped:   -24576
saturated: 32767

The conversion (int16_t)(a + b) is implementation-defined in C when the value does not fit, and typical compilers wrap, as shown. The widened addition in q15_add_sat happens in 32 bits, where 24,576 plus 16,384 is 40,960, which sat16 clamps to 32,767. Whether to wrap or saturate is a design choice: counters and phase accumulators want wrapping, and signals want saturation.

Multiplication: widen, multiply, shift

Multiplying two Q15 numbers gives a number with 30 fractional bits, because the scales multiply. The product of the stored integers is a * b, and the true value is a * b / 2^30. To return to Q15, shift right by 15. The product needs 32 bits, since two 16-bit values can produce 31 bits of magnitude, so widen before multiplying:

qmul.cc
#include <stdint.h>
#include <stdio.h>

static int16_t q15_mul_floor(int16_t a, int16_t b)
{
    return (int16_t)(((int32_t)a * b) >> 15);
}

static int16_t q15_mul_round(int16_t a, int16_t b)
{
    return (int16_t)((((int32_t)a * b) + (1 << 14)) >> 15);
}

int main(void)
{
    int16_t half = 16384;       /* 0.5 */
    int16_t tenth = 3277;       /* 0.1 */

    printf("0.5 * 0.5 = %d\n", q15_mul_floor(half, half));
    printf("0.1 * 0.1 floor: %d\n", q15_mul_floor(tenth, tenth));
    printf("0.1 * 0.1 round: %d\n", q15_mul_round(tenth, tenth));
    return 0;
}
Text
0.5 * 0.5 = 8192
0.1 * 0.1 floor: 327
0.1 * 0.1 round: 328

16384 * 16384 is 268,435,456, and shifting right by 15 gives 8,192, which is 0.25. For the second case, 3277 * 3277 is 10,738,729, which divided by 32,768 is 327.72. Truncating gives 327 and rounding gives 328, closer to the true value of 327.68 for 0.01. Truncation always rounds down, a bias of half a step on average, which accumulates in long computations such as filters. Adding half a step before the shift, 1 << 14 here, rounds to nearest and removes the bias.

The right shift of a negative number is arithmetic on virtually all compilers, which means it rounds toward minus infinity. The C standard calls it implementation-defined, so a portable codebase documents the assumption in one place.

The one that overflows: minus one times minus one

Q15 can hold minus 1 but not plus 1. Multiply minus one by minus one and the true answer is plus one, which does not fit:

qmul_edge.cc
#include <stdint.h>
#include <stdio.h>

static int16_t sat16(int32_t x)
{
    if (x > INT16_MAX) return INT16_MAX;
    if (x < INT16_MIN) return INT16_MIN;
    return (int16_t)x;
}

int main(void)
{
    int16_t m1 = -32768;     /* -1.0 */
    int32_t product = ((int32_t)m1 * m1) >> 15;

    printf("raw product:  %ld\n", (long)product);
    printf("truncated:    %d\n", (int16_t)product);
    printf("saturated:    %d\n", sat16(product));
    return 0;
}
Text
raw product:  32768
truncated:    -32768
saturated:    32767

The product (-32768) * (-32768) is 1,073,741,824, shifted right by 15 is 32,768, one more than the maximum 16-bit value. Truncating to 16 bits wraps to minus 32,768, so minus one times minus one comes out as minus one. Saturating gives 32,767, the closest representable number to plus one. This is the single most common fixed-point bug in signal-processing code, because it only appears when both operands sit at the extreme. CMSIS-DSP's arm_mult_q15 saturates for this reason, and the dedicated post on saturating Q15 shows the portable version.

Division and the Q16.16 format

Division removes the scale, so to keep a fractional result you shift the numerator left first. In Q16.16, with the binary point 16 bits from the right, a quotient needs (a << 16) / b, and the shifted numerator needs 64 bits:

q1616.cc
#include <stdint.h>
#include <stdio.h>

typedef int32_t q16_16;

#define Q16_ONE 65536

static q16_16 q16_mul(q16_16 a, q16_16 b)
{
    return (q16_16)(((int64_t)a * b) >> 16);
}

static q16_16 q16_div(q16_16 a, q16_16 b)
{
    return (q16_16)(((int64_t)a << 16) / b);
}

static void q16_print(const char *label, q16_16 v)
{
    int32_t whole = v >> 16;
    int32_t frac = (int32_t)((((int64_t)(v & 0xFFFF)) * 1000) >> 16);
    printf("%s %ld.%03ld\n", label, (long)whole, (long)frac);
}

int main(void)
{
    q16_16 a = 98304;      /* 1.5 */
    q16_16 b = 147456;     /* 2.25 */

    q16_print("product", q16_mul(a, b));
    q16_print("quotient", q16_div(q16_mul(a, b), a));
    return 0;
}
Text
product 3.375
quotient 2.250

98304 is 1.5 times 65,536 and 147456 is 2.25 times 65,536. Their product, 14,495,514,624, shifted right by 16 is 221,184, which is 3.375. Dividing that by 1.5 shifts the numerator left by 16 and divides by 98,304 to give 147,456, which is 2.25. The helper prints the fractional part by multiplying the low 16 bits by 1,000 and shifting, which gives three decimal digits without any floating point; the printing post generalizes this.

Division is the expensive operation. A core without a hardware divider takes tens of cycles per divide, and a 64-by-32 divide takes several times that. The standard tactic is to avoid it: multiply by a precomputed reciprocal, or divide by powers of two with shifts.

Choose the format from the range

The hardest design step is picking m and n for each quantity. The method is mechanical.

First, find the largest absolute value the quantity can take, from the physics or the sensor datasheet. That sets m, the number of integer bits, as the smallest integer such that 2^m exceeds the maximum. A temperature that spans minus 40 to plus 125 degrees needs 7 integer bits, since 128 is greater than 125.

Second, decide the resolution you need. A temperature to 0.01 degrees needs n such that 2^-n is no larger than 0.01, so n = 7, since 1/128 is 0.0078. The format is then Q7.7 plus the sign bit: 15 bits, which fits in a 16-bit word with one bit to spare.

Third, check that intermediate results fit. A product of two such values needs 2 * (m + n + 1) bits. If that exceeds the word size of your widest integer type, restructure the computation or reduce the precision.

A tidy way to apply this is a table in the source of every module that uses fixed point, with one row per quantity: its format, its range, its resolution. Keep it next to the code, since the formats exist nowhere else.

A fixed-point filter

The most common use of fixed point is a filter. A first-order low-pass filter updates y toward the input x by a fraction alpha of the error each step: y = y + alpha * (x - y). With alpha in Q15 and the signal in plain integers, the update is an integer multiply and a shift:

lowpass.cc
#include <stdint.h>
#include <stdio.h>

static int32_t lowpass(int32_t y, int32_t x, int16_t alpha_q15)
{
    return y + (int32_t)(((int64_t)(x - y) * alpha_q15) >> 15);
}

int main(void)
{
    const int16_t alpha = 4096;     /* 0.125 in Q15 */
    int32_t y = 0;

    for (int i = 1; i <= 3; i++) {
        y = lowpass(y, 1000, alpha);
        printf("step %d: %ld\n", i, (long)y);
    }
    return 0;
}
Text
step 1: 125
step 2: 234
step 3: 329

With the input held at 1,000 and alpha of 0.125, the first output is 1,000 times 0.125, which is 125. The second adds (1000 - 125) * 0.125, which is 109.375, truncated to 109, giving 234. The third adds (1000 - 234) * 0.125 = 95.75, truncated to 95, giving 329. The true floating-point sequence would be 125, 234.4, 329.0, so the truncation error is under one unit here.

Truncation makes the filter settle slightly below the input. When the error x - y is smaller than 8, (x - y) * 0.125 is less than one and truncates to zero, so the output stops 7 units short: a dead band. For positive and negative errors the shift rounds differently, because an arithmetic shift rounds toward minus infinity. The fixes are rounding before the shift, as in the multiplication above, or keeping extra fractional bits in the state, which is the usual approach in serious filters and is the reason accumulators are often wider than the signal.

Combining different formats

Real programs mix formats: a Q15 coefficient times a 12-bit ADC count, a Q16.16 position plus a Q24.8 offset. Three rules cover every case.

Adding or subtracting needs the same format. To add a Q24.8 number to a Q16.16 number, shift the first left by 8 to align the binary points, add, and decide the format of the result. A mismatch is not detected by the compiler, and the result is wrong by a power of two, which makes it hard to spot.

Multiplying adds the fractional bits. A Qa times a Qb product has a + b fractional bits. Shift right by the number of bits you want to drop, and by the time you return to a smaller format, check for overflow. Q15 times Q15 gives 30 fractional bits and needs a shift of 15 to return to Q15. Q15 times a plain integer gives an integer with 15 extra fractional bits, so shift by 15 to get a plain integer result.

Dividing subtracts the fractional bits. Qa / Qb has a - b fractional bits, so to keep n in the result, shift the numerator left by n + b - a first.

A table of formats at the top of a module, with one line per variable and its Q format, is the cheapest defence against mixing mistakes. Name variables with the format when it is not obvious: gain_q15, pos_q16_16.

Look-up tables with interpolation

Functions such as sine have no cheap fixed-point formula, so firmware uses a table. A quarter-wave table of nine entries plus linear interpolation gives a respectable Q15 sine from a 16-bit phase, where 65,536 is one full turn:

qsin.cc
#include <stdint.h>
#include <stdio.h>

/* sin(k * 11.25 degrees) in Q15 for k = 0..8, plus a repeated last entry */
static const int16_t tbl[10] = {
    0, 6393, 12540, 18205, 23170, 27246, 30274, 32138, 32767, 32767
};

static int16_t q15_sin(uint16_t phase)
{
    uint16_t quad = phase >> 14;
    uint16_t off = phase & 0x3FFF;
    if (quad & 1)
        off = (uint16_t)(0x4000 - off);          /* mirror the second and fourth quadrants */

    unsigned i = off >> 11;                      /* 8 intervals per quadrant */
    unsigned f = off & 0x7FF;                    /* position inside the interval */
    int32_t v = tbl[i] + (((int32_t)(tbl[i + 1] - tbl[i]) * (int32_t)f) >> 11);

    return (int16_t)((quad & 2) ? -v : v);       /* negate the lower half */
}

int main(void)
{
    uint16_t phases[] = { 0x0000, 0x0C00, 0x2000, 0x4000, 0x8000, 0xC000 };

    for (int i = 0; i < 6; i++)
        printf("phase 0x%04X -> %6d\n", phases[i], q15_sin(phases[i]));
    return 0;
}
Text
phase 0x0000 ->      0
phase 0x0C00 ->   9466
phase 0x2000 ->  23170
phase 0x4000 ->  32767
phase 0x8000 ->      0
phase 0xC000 -> -32767

Phase 0x2000 is 45 degrees, exactly on a table entry, so the result is 23,170, which is 0.7071 times 32,768. Phase 0x0C00 is 16.875 degrees, between the entries for 11.25 and 22.5 degrees. The interpolation gives 6,393 plus half the difference, 9,466, against a true value of 9,512, an error of 46 counts or about 0.14 percent. A larger table or a quadratic term shrinks it. The table repeats the last entry so that tbl[i + 1] is valid when off equals 0x4000. The result at 90 degrees is 32,767, one count short of exact, because Q15 cannot represent 1.0; the result at 270 degrees is minus 32,767, and the true value of minus 32,768 is reachable only by special-casing.

The same pattern, a coarse table and an interpolation, serves for logarithms, square roots, thermistor curves and gamma correction. Tables are stored in flash, cost no run time beyond the lookup, and are easy to test.

Rounding: where bias comes from

Every shift that drops bits is a rounding decision, and the choice matters when many operations accumulate.

MethodHowBias
Truncate (arithmetic shift)x >> nRounds toward minus infinity; mean error of half a step downward
Round half up(x + (1 << (n - 1))) >> nSmall positive bias on exact ties
Round half to evenLike half up, but ties go to the nearest even valueNo bias, a few more instructions
Round toward zeroDivide by 1 << nSymmetric, and slower than a shift on some cores

Round half up is the usual compromise. Use it in the inner multiply of a filter, and the output stops settling short of the input. For a stateful filter, keeping extra bits in the state variable matters more than the rounding method: a state with eight more fractional bits than the output has a rounding error 256 times smaller in the feedback path.

Headroom and accumulators

A sum of N values needs log2(N) extra bits to avoid overflow. Sixteen Q15 samples sum to at most 16 * 32,767, which is 524,272, fine in a 32-bit accumulator and impossible in 16 bits. That is why DSP code accumulates in 32 or 40 bits and converts back at the end, and why the ARM multiply-accumulate instructions produce 64-bit results.

A moving average over a window of 16 is then an accumulate and a shift by 4, with no overflow:

avg16.cc
#include <stdint.h>
#include <stdio.h>

static int16_t average16(const int16_t *x)
{
    int32_t sum = 0;
    for (int i = 0; i < 16; i++)
        sum += x[i];
    return (int16_t)(sum >> 4);
}

int main(void)
{
    int16_t samples[16];
    for (int i = 0; i < 16; i++)
        samples[i] = 30000;      /* near full scale */

    printf("average: %d\n", average16(samples));
    return 0;
}
Text
average: 30000

Sixteen samples of 30,000 sum to 480,000, which does not fit in 16 bits and fits in a 32-bit accumulator. Shifting by 4 divides by 16 and gives 30,000. A 16-bit accumulator in this program would have wrapped and returned nonsense.

Library support: CMSIS-DSP

On Arm cores you do not have to write every operation. CMSIS-DSP defines the types q7_t, q15_t and q31_t and provides vector functions that use the core's saturating and dual-multiply instructions where they exist. The functions most used are arm_add_q15, arm_mult_q15, arm_float_to_q15, arm_q15_to_float and the filter families such as arm_biquad_cascade_df1_q15. They saturate rather than wrap:

cmsis.cc
#include "arm_math.h"

void demo(void)
{
    q15_t a[2] = { 16384, -32768 };     /* 0.5 and -1.0 */
    q15_t b[2] = { 16384, -32768 };
    q15_t out[2];

    arm_mult_q15(a, b, out, 2);
    /* out[0] is 8192 (0.25); out[1] is 32767, saturated, not -32768 */
}

arm_mult_q15 multiplies element by element, shifts right by 15, and saturates, so the minus one times minus one case returns 32,767. These functions are documented in the CMSIS-DSP reference, including the exact rounding of each. Use the library for vectors and filters, and use your own scalar code for the odd operation the library lacks. A caution: the library's biquad filter takes a post-shift argument that scales the coefficients, a common source of surprise, so read its documentation before relying on gain.

Test against a reference

Fixed-point code is easy to get subtly wrong, and the check is cheap: compare it with double arithmetic on a grid of inputs, on a desktop. This test checks the rounded Q15 multiply on 1,024 input pairs spanning the whole range, including the saturation corner:

qtest.cc
#include <math.h>
#include <stdint.h>
#include <stdio.h>

static int16_t sat16(int32_t x)
{
    if (x > INT16_MAX) return INT16_MAX;
    if (x < INT16_MIN) return INT16_MIN;
    return (int16_t)x;
}

static int16_t q15_mul_round_sat(int16_t a, int16_t b)
{
    return sat16((((int32_t)a * b) + (1 << 14)) >> 15);
}

int main(void)
{
    int checked = 0, bad = 0;

    for (int i = -16; i < 16; i++) {
        for (int j = -16; j < 16; j++) {
            int16_t a = (int16_t)(i * 2048), b = (int16_t)(j * 2048);
            double exact = (double)a * b / 32768.0;
            if (exact > 32767.0) exact = 32767.0;       /* the saturation corner */
            double got = q15_mul_round_sat(a, b);
            if (fabs(got - exact) > 0.5 + 1e-9)
                bad++;
            checked++;
        }
    }
    printf("%d pairs checked, %d outside 0.5 LSB\n", checked, bad);
    return 0;
}
Text
1024 pairs checked, 0 outside 0.5 LSB

The bound of half a count is what rounding to nearest guarantees. If you replace the rounding with truncation, the same test reports many failures, which is how you confirm that the test can fail. Put tests like this in the repository and run them on every change, since fixed-point bugs hide behind plausible results.

Mistakes that cost the most time

MistakeSymptomPrevention
Multiplying in 16 bitsGarbage after the shiftCast one operand to int32_t before the multiply
Minus one times minus oneSign flip at full scaleSaturate the result
Mixed formats addedResults off by a power of twoAlign binary points, document each variable's Q format
Relying on >> for negative values in portable codeDifferent results on another compilerDocument the assumption, or divide
Signed overflow in plain intUndefined behavior, odd optimizer resultsUse wider types or unsigned arithmetic for wrapping
Truncating in a feedback pathDead band, output stops shortRound, or keep extra state bits
int that is 16 bits on the targetIntermediate overflow when the code was written on a 32-bit machineUse int32_t explicitly

The signed-overflow row deserves emphasis. In C, overflowing a signed integer is undefined behavior, and an optimizer may assume it never happens. A wrap you rely on must be done with unsigned types, where wraparound is defined.

The last step of many fixed-point programs is showing a number to a human. A printf with %f pulls the floating-point formatting code into the image, and on some embedded C libraries it is disabled by default. The printing post shows how to format a Q value with integer arithmetic, and the Q16.16 helper earlier in this guide is the core of it: print the integer part, then a fixed number of decimal digits computed by multiplying the fraction by a power of ten and shifting.

Scaling an ADC reading to engineering units

Most fixed-point code starts at an ADC. A 12-bit converter with a 3.3 V reference returns 0 to 4,095 counts, and a program wants millivolts. The exact conversion is mv = counts * 3300 / 4095. Multiply first and divide last, so the division does not discard precision, and add half the divisor before dividing to round to nearest:

adc_scale.cc
#include <stdint.h>
#include <stdio.h>

static uint32_t adc_to_mv(uint32_t counts)
{
    return (counts * 3300u + 4095u / 2u) / 4095u;
}

int main(void)
{
    uint32_t samples[] = { 0, 1, 2048, 4095 };

    for (int i = 0; i < 4; i++)
        printf("%4lu counts -> %4lu mV\n",
               (unsigned long)samples[i], (unsigned long)adc_to_mv(samples[i]));
    return 0;
}
Text
   0 counts ->    0 mV
   1 counts ->    1 mV
2048 counts -> 1650 mV
4095 counts -> 3300 mV

The largest intermediate value is 4095 * 3300, which is 13,513,500. It fits in a 32-bit unsigned integer and does not fit in 16 bits, which is the usual reason this expression goes wrong on an 8-bit or 16-bit core where int is narrow; the u suffixes and the uint32_t type force 32-bit arithmetic. A counts value of 2,048 is 1,650.4 millivolts, which rounds to 1,650.

Do the multiplication and the division in one expression rather than converting through an intermediate such as a "millivolts per count" constant. The constant 0.8059 millivolts per count has no exact integer form, and a rounded 1 millivolt per count would be off by a fifth. When the ratio genuinely has to be a constant, store it in a Q format with enough bits, and convert the product once at the end.

Square root and reciprocal

Some operations have no single instruction. Integer square root is the common one, since it appears in magnitudes and RMS values. The bit-by-bit method needs only shifts, compares and subtractions, and runs in a fixed number of steps:

isqrt.cc
#include <stdint.h>
#include <stdio.h>

static uint32_t isqrt64(uint64_t x)
{
    uint64_t res = 0, bit = 1ULL << 62;

    while (bit > x)
        bit >>= 2;
    while (bit) {
        if (x >= res + bit) {
            x -= res + bit;
            res = (res >> 1) + bit;
        } else {
            res >>= 1;
        }
        bit >>= 2;
    }
    return (uint32_t)res;
}

/* square root of a Q16.16 number, result in Q16.16 */
static uint32_t q16_sqrt(uint32_t a)
{
    return isqrt64((uint64_t)a << 16);
}

static void show(const char *label, uint32_t v)
{
    printf("%s %lu.%03lu\n", label, (unsigned long)(v >> 16),
           (unsigned long)(((uint64_t)(v & 0xFFFF) * 1000) >> 16));
}

int main(void)
{
    show("sqrt(2.0)  =", q16_sqrt(131072));
    show("sqrt(9.0)  =", q16_sqrt(589824));
    show("sqrt(0.25) =", q16_sqrt(16384));
    return 0;
}
Text
sqrt(2.0)  = 1.414
sqrt(9.0)  = 3.000
sqrt(0.25) = 0.500

The trick is in q16_sqrt. A Q16.16 number a represents a / 65536. Its square root is sqrt(a) / 256, and to return a Q16.16 result you need sqrt(a) * 256 = sqrt(a * 65536), so shift the argument left by 16 before taking the integer square root. For 2.0, the stored value is 131,072, and 131,072 * 65,536 is 8,589,934,592, whose integer square root is 92,681. That is 92,681 over 65,536, or 1.41420. The 64-bit type is needed, since the shifted value reaches 48 bits.

The reciprocal follows the divide rule: (1 << 32) / a for a Q16.16 a gives a Q16.16 reciprocal, again in 64 bits. Where a program divides by the same value many times, compute the reciprocal once and multiply, which turns a slow division into a multiplication and a shift.

A controller in fixed point

A proportional-integral controller shows the pieces working together: Q16.16 values, saturation, and a state variable that must not wind up. The controller sets an output, say a heater power in percent, from the error between a setpoint and a measurement:

pi.cc
#include <stdint.h>
#include <stdio.h>

typedef int32_t q16;

static q16 q16_mul(q16 a, q16 b) { return (q16)(((int64_t)a * b) >> 16); }
static q16 clamp(q16 v, q16 lo, q16 hi) { return v < lo ? lo : (v > hi ? hi : v); }

typedef struct { q16 kp, ki, integral; } pi_t;

static q16 pi_step(pi_t *c, q16 setpoint, q16 measured, q16 dt)
{
    q16 error = setpoint - measured;

    c->integral += q16_mul(error, dt);
    c->integral = clamp(c->integral, -50 * 65536, 50 * 65536);   /* anti-windup */

    q16 out = q16_mul(c->kp, error) + q16_mul(c->ki, c->integral);
    return clamp(out, 0, 100 * 65536);                           /* 0 to 100 percent */
}

static void show(q16 v)
{
    printf("%ld.%03ld\n", (long)(v >> 16), (long)(((int64_t)(v & 0xFFFF) * 1000) >> 16));
}

int main(void)
{
    pi_t c = { 2 * 65536, 65536 / 2, 0 };     /* kp = 2.0, ki = 0.5 */
    q16 dt = 6554;                            /* 0.1 s */
    q16 temps[] = { 40 << 16, 42 << 16, 45 << 16 };

    for (int i = 0; i < 3; i++)
        show(pi_step(&c, 50 << 16, temps[i], dt));
    return 0;
}
Text
20.500
16.900
11.150

With the setpoint at 50 degrees and the measurement at 40, the error is 10. The integral term accumulates 10 * 0.1 = 1, and the output is 2 * 10 + 0.5 * 1 = 20.5 percent. At 42 degrees the error is 8, the integral grows to 1.8, and the output is 16 + 0.9 = 16.9. At 45 it is 10 + 1.15 = 11.15. The 0.1 second step, 6,554 in Q16.16, is 0.100006, which the printed digits do not show.

The two clamps carry the engineering. The integral is limited to plus or minus 50, so a long error, such as a heater that cannot reach the setpoint, does not let the integral grow without bound and cause a large overshoot later; this is called anti-windup. The output is limited to 0 to 100 percent, so the controller never commands the impossible. Without the clamps in integer code, an overflow would wrap a large positive output into a large negative one.

Quantization error does not average away

A single rounding error is small, and it is tempting to assume that errors cancel. They do not when the same number is converted once and used many times. Converting 0.1 to a fixed-point format makes a fixed error, and summing it a thousand times multiplies that error by a thousand. The size of the step decides how bad it gets:

qerror.cc
#include <stdint.h>
#include <stdio.h>

int main(void)
{
    int32_t q8_8_step = 26;        /* 0.1 * 256 = 25.6, rounded to 26 */
    int32_t q16_16_step = 6554;    /* 0.1 * 65536 = 6553.6, rounded to 6554 */
    int32_t a = 0, b = 0;
    double d = 0.0;

    for (int i = 0; i < 1000; i++) {
        a += q8_8_step;
        b += q16_16_step;
        d += 0.1;
    }
    printf("Q8.8:   %.4f\n", a / 256.0);
    printf("Q16.16: %.4f\n", b / 65536.0);
    printf("double: %.4f\n", d);
    return 0;
}
Text
Q8.8:   101.5625
Q16.16: 100.0061
double: 100.0000

In Q8.8 the constant 0.1 becomes 26 over 256, which is 0.1015625, an error of 1.6 percent, and a thousand additions turn it into 1.56 units of drift. In Q16.16 the constant is 0.100006, and the thousand-fold error is 0.006. The lesson applies to every accumulating variable: an integrator, a counter of elapsed time, a phase accumulator. Give the state enough fractional bits that the representation error of the increment, multiplied by the number of steps you expect, stays below the tolerance of the result. A common fix is to keep the state at higher precision than the output, and to scale the increment from an exact ratio rather than from a rounded decimal.

For timekeeping, an exact ratio is often available: a 1 kHz tick is exactly one millisecond, and a 32.768 kHz crystal gives exactly 32,768 ticks per second. Use the integers and avoid the decimal approximations.

Budget the bits of a filter

A second-order filter, a biquad, shows how bit budgets are computed in practice. Its output is the sum of five products: three input terms and two output terms, each a coefficient times a sample. Suppose the samples are 16-bit values and the coefficients are Q14, so a coefficient can reach plus or minus 2.0 and has 14 fractional bits. A single product is at most 16 + 16 bits, 32 bits, so a 32-bit accumulator holds one product with no margin, and five can overflow it. The practical answer is a 64-bit accumulator, or a 32-bit accumulator with the products shifted down before the sum, which gives up precision.

The usual design on a Cortex-M4 or M7 uses the multiply-accumulate instructions that produce a 64-bit result, accumulates all five products, then shifts once. The shift count is the coefficient format's fractional bits, 14 here, and the result is saturated back to 16 bits. A single final rounding replaces five intermediate ones, and the error stays small. That is also why CMSIS-DSP's Q15 biquad takes a post-shift: coefficients larger than 1.0 do not fit in plain Q15, so the library stores them scaled down by a power of two and compensates after the accumulation.

When you design your own, write the maximum value of each intermediate on paper first. The exercise takes ten minutes, and catches the overflow that otherwise appears only when a real signal approaches full scale.

Narrow cores: 8-bit and 16-bit

On an 8-bit AVR or a 16-bit MSP430, the cost of a 32-bit multiply is large, since the hardware multiplies 8 or 16 bits at a time. Fixed point is still the right tool, and the choices shift. Use the smallest format that holds the range, because a 16-bit Q8.8 multiply is much cheaper than a Q16.16 one. Prefer shifts by multiples of 8, which the compiler can implement by moving whole bytes. Avoid division entirely where possible. And check what int means: on these targets it is 16 bits, so an expression such as a * b >> 15 on two int values overflows before the shift. Cast to int32_t explicitly, and look at the generated assembly if a hot loop is slow.

Compilers for these parts often provide fixed-point extensions, such as the _Fract and _Accum types of the ISO embedded C extensions in GCC for AVR, which let you write 0.5r and multiply with normal operators. They are convenient and non-portable, and many teams prefer explicit integer code that runs anywhere.

Reproducibility across platforms

Integer arithmetic gives the same bits on every machine, provided you stay inside what the C standard defines. Floating-point results can differ between compilers, optimization levels and FPU modes, which makes a recorded test hard to compare. A fixed-point algorithm that passes a bit-exact test on a desktop passes the same test on the target, which is a real engineering benefit for regression tests and for systems that must agree across nodes, such as a controller and its simulator.

The assumptions to write down are the ones C leaves open: the right shift of a negative signed value, the width of int, and the behavior of conversions that do not fit. State them in a header, check them with _Static_assert where possible, and test on both a 32-bit and a 64-bit host.

Write the formats into the code

Because the compiler cannot see a Q format, the code has to carry the information in names and in checks. Three habits make the formats visible. Give each format a type name, so a function signature says what it takes. Make constants through a macro that rounds, so a coefficient in the source reads as the real number you meant. And assert the assumptions the code depends on, so a port to a different compiler fails at build time and not in the field:

fixedpoint.hc
#include <stdint.h>

typedef int16_t q15_t;
typedef int32_t q16_16_t;

/* round to nearest; x must be a compile-time constant in [-1, 1) */
#define Q15(x)     ((q15_t)((x) * 32768.0 + ((x) < 0 ? -0.5 : 0.5)))
#define Q16_16(x)  ((q16_16_t)((x) * 65536.0 + ((x) < 0 ? -0.5 : 0.5)))

_Static_assert(sizeof(int) >= 4 || sizeof(long) >= 4, "need a 32-bit integer type");
_Static_assert((-8 >> 1) == -4, "arithmetic right shift is required");
_Static_assert(Q15(0.5) == 16384, "Q15 macro is broken");

The first two assertions state facts that the rest of the code assumes. The third is a self-test of the macro, evaluated at compile time, which catches a typo in the scale constant before it reaches any filter coefficient. A coefficient such as Q15(0.125) then documents itself and turns into the constant 4,096 with no run-time cost. A project that uses these names consistently can be searched for every use of a format, and a review can confirm that each function receives the format it expects.

When fixed point is the wrong tool

Cores with a fast FPU and no tight loop. A Cortex-M4F or M7 does a single-precision multiply in a cycle. Writing fixed point there trades readability for no gain, and the dynamic range of float removes whole classes of overflow bug.

Data with a huge dynamic range. A quantity that spans many decades, such as a power measurement from microwatts to kilowatts, needs a floating exponent. Fixed point would need 40 or more bits to cover it.

Prototype code. Write it in floating point first, verify the algorithm, then convert the inner loops once the design is stable and you have a reference to compare against. The test harness above is exactly that comparison.

Teams without the habit of testing. Fixed-point bugs are quiet. Without tests against a reference, the cost of a subtle scaling error in the field exceeds the savings in flash.

A path through the posts

Start with the beginner posts. The Q format explanation defines the notation and the range arithmetic, the float and Q15 conversion post covers rounding and compile-time constants, and the printing post shows output without float support. The intermediate posts cover saturating Q15 arithmetic and the CMSIS-DSP functions, and the advanced ones go into filters, trigonometry tables and error analysis. The sensors guide uses fixed point throughout: the BME280 compensation formulas are integer-only for the reason given at the start of this guide.

Taggedcbeginner
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.