Skip to content
systemcoding.dev
Embedded

Convert Between Floats and Q15 Fixed-Point Values

Convert floats to Q15 and back in C with rounding, saturation and NaN handling, build compile-time Q15 constants, and convert whole sample blocks safely.

7 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the Arm, C and GNU logos.

Sooner or later a fixed-point program has to meet a floating-point number. The filter coefficients came from a design tool as decimals. The test vectors were generated on a laptop. The sensor library returns floats. Converting between the two looks like one line of code, (int16_t)(x * 32768), and that line has three bugs: it truncates instead of rounding, it wraps when x is 1.0 or larger, and it has no answer for a NaN. This post writes the conversion correctly in C, shows the error each shortcut introduces with numbers you can check by hand, and covers the two variants you need in real code: compile-time constants for coefficients, and block conversion with a count of clipped samples. It assumes you know what Q15 means, as explained in the Q format post, which defines the notation used here.

For the library equivalents, see the arm_float_to_q15 and arm_q15_to_float functions in the CMSIS-DSP documentation. Older releases of that library truncated and newer ones round, so check the version you have before relying on either.

The plain conversion and what goes wrong

A Q15 value is the real number multiplied by 32,768 and stored in a 16-bit signed integer. The obvious code is:

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

int main(void)
{
    double x = 1.0;
    int16_t q = (int16_t)(x * 32768.0);

    printf("%.1f -> %d\n", x, q);
    return 0;
}
Text
1.0 -> -32768

The product is 32,768, which does not fit in a signed 16-bit integer. The cast wraps it around to minus 32,768, so plus one becomes minus one, the worst possible error. Converting a double that does not fit into an integer type is undefined behavior in C, and the wrap shown here is what most compilers produce for the narrowing step, not something to rely on. Any conversion routine must clamp first.

Round to nearest and saturate

The correct routine scales, clamps to the representable range, and rounds. Round half away from zero is simple and symmetric:

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

static int16_t float_to_q15(float x)
{
    if (isnan(x))
        return 0;

    float scaled = x * 32768.0f;
    if (scaled >= 32767.0f)
        return INT16_MAX;
    if (scaled <= -32768.0f)
        return INT16_MIN;
    return (int16_t)lroundf(scaled);
}

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

int main(void)
{
    float tests[] = { 0.1f, -0.1f, 0.5f, 0.99999f, 1.0f, -1.0f, 2.0f, NAN };

    for (int i = 0; i < 8; i++) {
        int16_t q = float_to_q15(tests[i]);
        printf("%9.5f -> %6d -> %9.5f\n", tests[i], q, q15_to_float(q));
    }
    return 0;
}
Text
  0.10000 ->   3277 ->   0.10001
 -0.10000 ->  -3277 ->  -0.10001
  0.50000 ->  16384 ->   0.50000
  0.99999 ->  32767 ->   0.99997
  1.00000 ->  32767 ->   0.99997
 -1.00000 -> -32768 ->  -1.00000
  2.00000 ->  32767 ->   0.99997
      nan ->      0 ->   0.00000

Walk through the rows. The value 0.1 scales to 3,276.8 and rounds to 3,277, which converts back to 0.100006, printed as 0.10001 at five digits. The value 0.99999 scales to 32,767.67, which is above the clamp threshold of 32,767, so it returns 32,767 and converts back to 0.99997. The values 1.0 and 2.0 clamp the same way, and minus 1.0 is exactly minus 32,768. A NaN becomes zero, which is a choice: a NaN in a signal path usually means a bug upstream, and zero is the least harmful value, but a debug build should assert instead.

The helper lroundf rounds half away from zero, so 0.5 LSB ties go outward. That is symmetric, which avoids a bias, and slower than a cast on a core without hardware float support. If conversion is on a hot path, use the integer-only variant at the end of this post.

Truncation versus rounding

Why does it matter? Compare the two on a few values, with the error measured in least significant bits:

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

int main(void)
{
    double xs[] = { 0.1, -0.1, 0.3, 0.5, 0.7 };

    for (int i = 0; i < 5; i++) {
        double exact = xs[i] * 32768.0;
        int16_t t = (int16_t)exact;              /* truncates toward zero */
        int16_t r = (int16_t)lround(exact);      /* rounds to nearest */
        printf("x=%5.2f exact=%9.1f trunc=%6d (%+.1f) round=%6d (%+.1f)\n",
               xs[i], exact, t, t - exact, r, r - exact);
    }
    return 0;
}
Text
x= 0.10 exact=   3276.8 trunc=  3276 (-0.8) round=  3277 (+0.2)
x=-0.10 exact=  -3276.8 trunc= -3276 (+0.8) round= -3277 (-0.2)
x= 0.30 exact=   9830.4 trunc=  9830 (-0.4) round=  9830 (-0.4)
x= 0.50 exact=  16384.0 trunc= 16384 (+0.0) round= 16384 (+0.0)
x= 0.70 exact=  22937.6 trunc= 22937 (-0.6) round= 22938 (+0.4)

Truncation errors are as large as one full count and always point toward zero, so positive values read low and negative values read high. Rounding errors never exceed half a count. For one conversion that is a difference of a fraction of a part in 30,000. For a table of 256 filter coefficients it can shift the filter's frequency response, and for a signal that is converted and summed, the one-directional bias adds up. Round unless you have a measured reason not to.

Constants at compile time

A filter coefficient is a number you type once, and writing 3277 for 0.1 hides its meaning and invites a transcription error. A macro converts at compile time, so the source says what you mean:

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

#define Q15(x)  ((int16_t)((x) * 32768.0 + ((x) < 0 ? -0.5 : 0.5)))

static const int16_t fir[3] = { Q15(0.25), Q15(0.5), Q15(0.25) };

int main(void)
{
    printf("%d %d %d\n", fir[0], fir[1], fir[2]);
    printf("%d\n", Q15(0.1));
    printf("%d\n", Q15(-0.7));
    return 0;
}
Text
8192 16384 8192
3277
-22938

The expression adds half before the cast, with the sign of the number, which gives rounding to nearest for both signs, because the cast truncates toward zero. For 0.1 it computes 3,276.8 + 0.5 = 3,277.3 and truncates to 3,277. For minus 0.7 it computes minus 22,937.6 minus 0.5, which is minus 22,938.1, and truncates to minus 22,938. The macro does not saturate, so Q15(1.0) produces 32,768 and wraps. Make the macro a constant expression only for values in range, and add a compile-time check: a _Static_assert on the largest coefficient, or a unit test that converts the whole table and compares it with the doubles.

The compiler evaluates the arithmetic in floating point at compile time, so there is no run-time cost and no floating-point code in the image, even on a core with no FPU.

Convert a block and count the clipping

Real signals arrive in blocks, and a conversion that silently clips hides a gain problem. Count the clipped samples, so a caller can notice:

block.cc
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

static size_t float_to_q15_block(const float *in, int16_t *out, size_t n)
{
    size_t clipped = 0;

    for (size_t i = 0; i < n; i++) {
        float s = in[i] * 32768.0f;
        if (s >= 32767.0f)       { out[i] = INT16_MAX; clipped++; }
        else if (s <= -32768.0f) { out[i] = INT16_MIN; clipped++; }
        else                     { out[i] = (int16_t)lroundf(s); }
    }
    return clipped;
}

int main(void)
{
    float in[5] = { 0.25f, 1.2f, -0.5f, -1.7f, 0.9999f };
    int16_t out[5];

    size_t clipped = float_to_q15_block(in, out, 5);
    printf("%d %d %d %d %d, clipped %zu\n", out[0], out[1], out[2], out[3], out[4],
           clipped);
    return 0;
}
Text
8192 32767 -16384 -32768 32765, clipped 2

The values 1.2 and minus 1.7 are out of range and counted. The value 0.9999 scales to 32,764.7 and rounds to 32,765, below the clamp. A caller that sees a nonzero count can reduce the gain, log a warning or raise a flag. Clipping a sample is lossy, and doing it silently is how a distorted output goes unnoticed for weeks.

The block form is also the right shape for a DMA callback or an audio buffer. Process the whole buffer in one call and keep the inner loop free of function calls.

Convert Q15 back for display or logging

Going the other way, the division by 32,768 is exact in floating point, because it only changes the exponent, so there is nothing to round. If you must avoid floating point, convert straight to a decimal string with integer arithmetic, which is what the printing post does. Another common destination is a fixed unit: a Q15 that represents a fraction of a 3.3 V full scale becomes millivolts with (q * 3300) >> 15, with the multiplication widened to 32 bits first.

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

static int32_t q15_to_mv(int16_t q)
{
    return ((int32_t)q * 3300) >> 15;
}

int main(void)
{
    printf("%ld %ld %ld\n", (long)q15_to_mv(16384), (long)q15_to_mv(32767), (long)q15_to_mv(-32768));
    return 0;
}
Text
1650 3299 -3300

Half scale is 1,650 millivolts, as expected. Full positive scale is 3,299, one short of 3,300, since Q15 cannot reach 1.0, and negative full scale is exactly minus 3,300. The right shift floors negative values, so a value such as minus 1 maps to minus 1 millivolt and not zero; add the rounding term, + (1 << 14), if that matters.

Mistakes to avoid

MistakeEffect
Casting x * 32768 without clampingWrap at plus one and above, a sign flip
Truncating instead of roundingA downward error of up to one count, with a bias
Using the macro on out-of-range constantsSilent wrap at compile time
Converting a NaNUndefined behavior; guard with isnan
Forgetting that 1.0 is not representableAn off-by-one at full scale
Dividing by 32767 instead of 32768A scale error of 0.003 percent that never shows in a quick test

The last row is a classic. Using 32,767 as the scale makes plus one exactly representable and breaks everything else by a hair, and the test with the extremes still passes. Use 32,768 for both directions.

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.