Skip to content
systemcoding.dev
Embedded

Multiply and Divide Fixed-Point Numbers Without Overflow

Widen before you multiply, shift with rounding, pre-scale before you divide, and saturate the result. Q15 and Q16.16 routines in portable C that never overflow.

6 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Arm, C and Nordic Semiconductor logos.

A fixed-point multiply is two operations wearing one symbol: an integer multiply that doubles the number of bits, and a shift that throws half of them away. Overflow hides in both. The multiply overflows when you do it in a type as narrow as the operands, and the shift overflows when the true result does not fit the format you shift it back into. This post builds multiply and divide for Q15 and Q16.16 in portable C (C99 and later, with <stdint.h>) so that neither step can wrap silently. If the notation is new, the Q format explainer comes first; here we assume you can read Q15 as "a 16-bit signed integer with 15 fraction bits".

Why the naive multiply fails

Take two Q15 values. A Q15 number x stores x * 32768 in an int16_t, so the range is -32768 to 32767, which is -1.0 to just under 1.0. Multiplying the raw integers gives a * b = (A * 32768) * (B * 32768) = A * B * 2^30. That has 30 fraction bits, so you must shift right by 15 to get back to Q15.

The first bug is writing this in 16 bits:

c
int16_t q15_mul_bad(int16_t a, int16_t b)
{
    return (a * b) >> 15;   /* looks fine, is not */
}

In C, a * b is computed after integer promotion. On a target where int is 32 bits, such as a Cortex-M, both operands promote to int, the product fits, and the code works. On an AVR or MSP430 where int is 16 bits, the same line overflows, which is undefined behavior for signed types. The fix is to say what you mean and widen explicitly with a cast to int32_t, so the code is correct on every target.

Widen, round, shift, saturate

A correct Q15 multiply has four steps, and each has a reason.

  1. Widen. Cast one operand to int32_t so the multiply happens in 32 bits. Two 16-bit signed values multiply into at most 31 significant bits plus sign, which always fits.

  2. Round. Add 1 << 14 (half of 1 << 15) before the shift. Without it, the shift truncates toward negative infinity and every result is biased low. Rounding and truncation bias gets its own post; for now know that the extra add costs one instruction and removes a systematic error.

  3. Shift. An arithmetic right shift by 15. Right-shifting a negative signed value is implementation-defined in C, but every compiler for the targets that matter (GCC, Clang, IAR, Arm Compiler) documents it as an arithmetic shift, and the shift is what the code means.

  4. Saturate. One input pair overflows the format: -1.0 * -1.0 = +1.0, which Q15 cannot represent. Clamp to 32767 instead of letting it wrap to -32768.

q15.hc
#include <stdint.h>

#define Q15_ONE_MINUS_LSB  INT16_MAX   /* 32767, about 0.99997 */
#define Q15_MIN            INT16_MIN   /* -32768, exactly -1.0 */

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

static inline int16_t q15_mul(int16_t a, int16_t b)
{
    int32_t p = (int32_t)a * (int32_t)b;   /* Q30 */
    p += (int32_t)1 << 14;                 /* round to nearest */
    return q15_sat(p >> 15);
}

The saturate helper is separate on purpose. You will use it after additions too, and one tested clamp beats five hand-rolled ones.

Check it with worked values

Pick inputs whose results you can verify by hand.

main.cc
#include <stdio.h>
#include "q15.h"

int main(void)
{
    int16_t half    = 16384;   /* 0.5  */
    int16_t quarter = 8192;    /* 0.25 */
    int16_t minus1  = INT16_MIN;

    printf("0.5 * 0.25   = %d\n", q15_mul(half, quarter));
    printf("-1.0 * -1.0  = %d\n", q15_mul(minus1, minus1));
    printf("0.5 * -0.5   = %d\n", q15_mul(half, -half));
    return 0;
}
Text
0.5 * 0.25   = 4096
-1.0 * -1.0  = 32767
0.5 * -0.5   = -8192

Work the first one: 16384 * 8192 = 134217728, plus 16384 is 134234112, and shifting right by 15 gives 4096, which is 0.125. The second is the saturating case: the raw product is 1073741824, which shifted is 32768, and the clamp returns 32767. The third shows the rounding behavior on negative numbers: -134217728 + 16384 shifted right by 15 is -8192, which is -0.25, as expected.

Q16.16: the same shape with 64 bits

Q16.16 stores a 32-bit signed integer with 16 fraction bits. The product of two of them needs 64 bits, so the widening cast goes to int64_t. The saturation bounds become INT32_MAX and INT32_MIN.

q16.hc
#include <stdint.h>

static inline int32_t q16_sat(int64_t x)
{
    if (x > INT32_MAX) return INT32_MAX;
    if (x < INT32_MIN) return INT32_MIN;
    return (int32_t)x;
}

static inline int32_t q16_mul(int32_t a, int32_t b)
{
    int64_t p = (int64_t)a * (int64_t)b;   /* Q32 */
    p += (int64_t)1 << 15;                 /* round */
    return q16_sat(p >> 16);
}

With a = 3.5 stored as 229376 and b = 2.25 stored as 147456, the 64-bit product is 33822867456. Add 32768, shift right by 16, and you get 516096, which is 7.875 in Q16.16. A 32-bit multiply would have wrapped long before that. On a Cortex-M3 or M4 the compiler turns the 64-bit product into one SMULL instruction, so widening costs nothing extra there. On a Cortex-M0, which has only a 32-bit multiplier, the compiler calls a runtime helper (__aeabi_lmul), and the 64-bit path is slower. That is a measurement for your own chip, and it is the reason fixed-point versus float on MCUs is a decision, not a default.

Division: scale the numerator first

Division goes the other way. Dividing two Q15 raw values gives (A * 2^15) / (B * 2^15) = A / B, a plain ratio with no fraction bits. To get a Q15 result you must multiply the numerator by 2^15 first, and that is where overflow lives: the numerator needs 31 bits, so it must be widened before the shift.

q15div.hc
static inline int16_t q15_div(int16_t a, int16_t b)
{
    if (b == 0) {
        return a >= 0 ? INT16_MAX : INT16_MIN;   /* saturate, do not trap */
    }
    int32_t num = ((int32_t)a) << 15;            /* Q30 */
    /* round to nearest: add half the divisor, matching the sign */
    int32_t half = (int32_t)(b > 0 ? b : -b) / 2;
    num += ((num >= 0) == (b > 0)) ? half : -half;
    return q15_sat(num / b);
}

Three details deserve attention. Left-shifting a negative signed value is undefined behavior in C before C23 for some cases, so if your coding standard forbids it, write ((int32_t)a) * 32768 instead; the compiler emits the same code. The zero check returns a saturated value because on many MCUs an integer divide by zero either traps or returns garbage, and neither is acceptable in a control loop. And the result can overflow the format whenever |a| > |b|, which is exactly what q15_sat is for.

c
printf("0.25 / 0.5  = %d\n", q15_div(8192, 16384));
printf("0.75 / 0.5  = %d\n", q15_div(24576, 16384));
printf("0.25 / 0    = %d\n", q15_div(8192, 0));
Text
0.25 / 0.5  = 16384
0.75 / 0.5  = 32767
0.25 / 0    = 32767

8192 << 15 is 268435456, divided by 16384 is 16384, which is 0.5. The second line is 1.5 in real arithmetic, which Q15 cannot hold, so it saturates to 32767. Whether saturating is right depends on the caller; a filter should clamp, while a safety check should flag the overflow instead.

Detect overflow when you cannot saturate

Sometimes the right response to an out-of-range result is to report it. Make the helper return a status and the value through a pointer:

c
static inline int q15_mul_checked(int16_t a, int16_t b, int16_t *out)
{
    int32_t r = ((int32_t)a * (int32_t)b + ((int32_t)1 << 14)) >> 15;
    if (r > INT16_MAX || r < INT16_MIN) {
        *out = q15_sat(r);
        return -1;
    }
    *out = (int16_t)r;
    return 0;
}

Only the -1.0 * -1.0 pair trips it for multiplication, so for Q15 a single special case would do. Division and addition have many more failing inputs, and the uniform check keeps the rule simple.

Where this does not fit

If your values span many orders of magnitude, a fixed binary point is the wrong tool. A sensor reading that goes from microvolts to volts will either lose its small end or overflow its large end in any single Q format. Use floating point if the part has an FPU, or a block floating-point scheme where a shared exponent travels with an array. If the chip has the Cortex-M4 DSP extension, the __SSAT and __QADD16 intrinsics from CMSIS do the saturation in hardware, and the CMSIS-DSP Q15 functions already contain tested versions of everything above. Reach for a hand-written routine when you need the behavior on a core without them, or when you want the code to build and test on a laptop.

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.