Skip to content
systemcoding.dev
Embedded

Print Fixed-Point Values Without printf Float Support

Print Q15 and Q16.16 numbers as decimals in C with integer arithmetic only: split, round, pad the fraction, carry, handle the sign, skip printf float code.

7 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.

You spent the project avoiding floating point, and then the program has to show a temperature. The obvious move is printf("%f", x), which on an embedded C library either prints nothing useful or drags in thousands of bytes of floating-point formatting code. With newlib-nano, the small C library used by most Arm GCC projects, %f is disabled by default and prints a blank or a literal f until you link with a special flag that adds several kilobytes. AVR's libc has a similar switch. The way out is to print the fixed-point number with integer arithmetic only: split it into a whole part and a fraction, scale the fraction into decimal digits, round it, and pad it with zeros. It takes thirty lines of C, runs anywhere, and gives exactly the digits you ask for. This post writes that formatter for any Q format, tests it on the cases that break naive versions, and shows the library settings it replaces. It assumes you know what Q15 and Q16.16 mean, as in the Q format post.

The library behavior is documented in newlib's notes on printf with the nano specs, and in the AVR libc manual under vfprintf. Check your toolchain's documentation, since defaults differ.

Why %f is a problem

The flag is --specs=nano.specs, and newlib-nano ships a printf that leaves out floating-point support to save space. If you call printf("%f", x), the result is a line with no number. Turning it on needs the linker option -u _printf_float, and the cost is a few kilobytes of flash plus extra RAM use. On a part with 16 KB of flash that can be the difference between fitting and not.

ToolchainDefault for %fTo enableCost
Arm GCC with newlib-nanoNot supportedLink with -u _printf_floatSeveral kilobytes of flash
AVR libcNot supported in the default vfprintfLink with -Wl,-u,vfprintf -lprintf_flt -lmA larger vfprintf
Arm GCC with full newlibSupportedNothingLarge

The fixed-point formatter below avoids the whole issue. It also gives you something printf does not: control. You choose the number of decimals and the rounding, and you get identical output on every platform.

Split a Q value into digits

A Q number is an integer divided by 2^n. Its whole part is the integer shifted right by n. Its fractional part is the remaining n bits, a fraction of one. To print d decimal digits, multiply the fraction by 10^d and shift right by n, which gives the fraction as an integer between 0 and 10^d:

For the Q16.16 value 3.375, stored as 221,184:

  • whole part: 221,184 shifted right by 16 is 3

  • fraction bits: 221,184 minus 3 times 65,536, which is 24,576

  • three decimals: 24,576 times 1,000 divided by 65,536 is 375

so the output is 3.375. Rounding the fraction needs half a unit added before the shift, which is 65,536 / 2 here.

The formatter

The version below works for any format from 1 to 31 fractional bits and up to six decimals. It uses 64-bit arithmetic internally, since the multiplication of a 31-bit fraction by a million does not fit in 32 bits:

fxprint.cc
#include <stddef.h>
#include <stdint.h>

static char *put_uint(char *p, uint64_t v, unsigned min_digits)
{
    char tmp[20];
    unsigned n = 0;

    do {
        tmp[n++] = (char)('0' + (unsigned)(v % 10));
        v /= 10;
    } while (v != 0 || n < min_digits);

    while (n)
        *p++ = tmp[--n];
    return p;
}

/* writes a NUL-terminated string; out must hold at least 24 bytes */
void fx_to_str(char *out, int64_t v, unsigned frac_bits, unsigned decimals)
{
    static const uint32_t pow10[7] = { 1, 10, 100, 1000, 10000, 100000, 1000000 };
    char *p = out;

    if (decimals > 6)
        decimals = 6;
    uint64_t scale = pow10[decimals];

    int negative = v < 0;
    uint64_t mag = negative ? (uint64_t)(-v) : (uint64_t)v;
    uint64_t one = 1ULL << frac_bits;

    uint64_t whole = mag >> frac_bits;
    uint64_t frac = ((mag & (one - 1)) * scale + (one >> 1)) >> frac_bits;

    if (frac >= scale) {              /* rounding carried into the whole part */
        whole++;
        frac -= scale;
    }
    if (whole == 0 && frac == 0)
        negative = 0;                 /* never print "-0.000" */

    if (negative)
        *p++ = '-';
    p = put_uint(p, whole, 1);
    if (decimals > 0) {
        *p++ = '.';
        p = put_uint(p, frac, decimals);
    }
    *p = '\0';
}

Go through the pieces that matter.

put_uint writes an unsigned number in decimal, with a minimum digit count that pads with zeros on the left. That is what makes 0.05 print as 0.05 and not 0.5: the fraction 5 must become 05 with two decimals. The loop collects digits in reverse and copies them out forward.

The magnitude is taken as an unsigned 64-bit value before the split. Splitting a negative number with a right shift would floor toward minus infinity and give a wrong fraction, so handle the sign separately and work on the absolute value. The cast of -v works for every int64_t except the most negative value, which a 32-bit Q number can never be.

The fraction is (low bits * scale + half) >> frac_bits. Adding one >> 1 rounds to nearest. If the rounded fraction reaches scale, which happens for 2.9996 printed with three decimals, the code carries one into the whole part and subtracts the scale, so the output is 3.000 and not 2.1000.

The sign is dropped when both parts are zero, so a tiny negative number prints as 0.000 and not -0.000.

Test the awkward cases

The cases that break a hurried formatter are the zero padding, the carry, the sign and the extremes. This test covers them for Q16.16 and Q15:

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

void fx_to_str(char *out, int64_t v, unsigned frac_bits, unsigned decimals);

static void show(const char *label, int64_t v, unsigned bits, unsigned decimals)
{
    char buf[24];
    fx_to_str(buf, v, bits, decimals);
    printf("%-22s %s\n", label, buf);
}

int main(void)
{
    show("Q16.16  3.375, 3 dec", 221184, 16, 3);
    show("Q16.16 -1.5, 3 dec", -98304, 16, 3);
    show("Q16.16  2.9996, 3 dec", 196583, 16, 3);
    show("Q16.16  0.05, 2 dec", 3277, 16, 2);
    show("Q16.16 -0.0004, 3 dec", -26, 16, 3);
    show("Q15     0.5, 4 dec", 16384, 15, 4);
    show("Q15    -1.0, 2 dec", -32768, 15, 2);
    show("Q15     0.1, 5 dec", 3277, 15, 5);
    show("Q16.16  7, 0 dec", 458752, 16, 0);
    return 0;
}
Text
Q16.16  3.375, 3 dec   3.375
Q16.16 -1.5, 3 dec     -1.500
Q16.16  2.9996, 3 dec  3.000
Q16.16  0.05, 2 dec    0.05
Q16.16 -0.0004, 3 dec  0.000
Q15     0.5, 4 dec     0.5000
Q15    -1.0, 2 dec     -1.00
Q15     0.1, 5 dec     0.10001
Q16.16  7, 0 dec       7

Check the less obvious rows by hand. The value 3,277 in Q16.16 is 0.05000, and with two decimals the fraction is (3277 * 100 + 32768) >> 16, which is 360,468 over 65,536, or 5.5, truncated to 5, and padded to 05, giving 0.05. The value 196,583 is 2.99960, whose three-decimal fraction rounds to 1,000, which equals the scale, so the code carries to give 3.000. The value minus 26 is minus 0.0004, whose fraction rounds to 0; both parts are zero, so the sign is dropped. In the Q15 cases, 3,277 over 32,768 is 0.100006, printed with five decimals as 0.10001, since the fraction 0.100006 rounds up. The last case, 458,752 in Q16.16, is 7.0, and with zero decimals the code prints 7 with no point.

Use it in place of printf

Create the string, then send it through whatever output you have: a UART function, an LCD driver, a log buffer. No %f is involved:

log.cc
#include <stdint.h>

void fx_to_str(char *out, int64_t v, unsigned frac_bits, unsigned decimals);
void uart_puts(const char *s);

void log_temperature(int32_t temp_q8_8)
{
    char buf[24];

    uart_puts("temp = ");
    fx_to_str(buf, temp_q8_8, 8, 2);
    uart_puts(buf);
    uart_puts(" C\r\n");
}

If the temperature in Q8.8 is 6,208, which is 24.25 degrees, the UART shows:

Text
temp = 24.25 C

The same function formats any Q format, so one routine serves the whole program, and it needs no heap, no malloc, and no locale. If your library has snprintf without float, you can also build the number with %lu.%0*lu from the two parts, using * to pass the digit count. The manual loop above avoids the dependency on a formatting engine entirely, which saves the larger part of the code size on tiny parts.

Printing plain scaled integers

Often there is no Q format at all: a sensor returns tenths of a degree as an integer, such as 245 for 24.5 degrees. The same technique applies with a decimal scale in place of a binary one: print v / 10, a point, and v % 10, taking care with negatives, where -5 / 10 is 0 and -5 % 10 is minus 5 in C. Handle the sign first and work on the absolute value, as the formatter does.

tenths.cc
#include <stdio.h>

static void print_tenths(int v)
{
    int neg = v < 0;
    unsigned a = (unsigned)(neg ? -v : v);

    printf("%s%u.%u\n", neg ? "-" : "", a / 10, a % 10);
}

int main(void)
{
    print_tenths(245);
    print_tenths(-5);
    print_tenths(0);
    return 0;
}
Text
24.5
-0.5
0.0

The case -5 is the one that goes wrong without the sign split: the integer division gives 0, the remainder is minus 5, and a naive printf("%d.%d", v / 10, v % 10) prints 0.-5. Splitting the sign first fixes it.

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.