Skip to content
Tactiverge

Units, scaling and fixed-point arithmetic

Doing accurate maths with integers on small processors: choosing scaled units, ordering operations to avoid truncation and overflow, and Q-format fixed point.

Lesson 5 of 6 · 30 min · Self-paced · Free

Why not just use floats?

On a laptop, float and double arithmetic is fast and you rarely think about it. Many small microcontrollers have no hardware floating-point unit. The compiler still lets you write float, but each operation becomes a call into a software library: slower, larger in flash, and sometimes too slow for a fast control loop. Even on chips with floating-point hardware, integers remain attractive for interrupt handlers, compact data logs and messages between devices.

The alternative is to do maths with integers, deliberately scaled so they keep enough precision. Done carefully, this is fast and exact. Done carelessly, it produces some of the most baffling bugs in embedded systems. This lesson builds on fixed-width types and overflow from the programming-foundations module.

Units first

Before any arithmetic, decide what every number means. A variable called temp holding 2500 is ambiguous: 2500 °C? 25.00 °C? 2500 counts? Good firmware puts the unit in the name:

int32_t temp_cdeg;    /* hundredths of a degree Celsius: 2500 means 25.00 °C */
int32_t battery_mv;   /* millivolts                                          */
uint32_t uptime_ms;   /* milliseconds since start-up                         */

Choosing a smaller unit, such as millivolts instead of volts or centidegrees instead of degrees, is the simplest form of fixed point. The integer counts tiny steps, and the step size sets the resolution. Millivolts give a resolution of 0.001 V with no fractions at all.

Unit confusion is not a beginner's problem. NASA's Mars Climate Orbiter was lost in 1999 partly because one piece of software produced results in pound-force seconds while another expected newton-seconds. Labelled units are cheap insurance.

Order of operations matters

Converting a 12-bit ADC reading to millivolts with a 3.3 V reference means calculating counts × 3300 / 4096. In integer maths, the order and the width of the variables change the answer completely:

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

int main(void)
{
    uint16_t counts = 2000;                  /* 12-bit ADC reading */

    /* Wrong 1: divide first. 2000 / 4096 is 0 in integer maths. */
    int32_t mv_div_first = counts / 4096 * 3300;

    /* Wrong 2: a 16-bit intermediate overflows (2000 * 3300 = 6,600,000). */
    uint16_t mv_16bit = (uint16_t)(counts * 3300u);

    /* Right: widen to 32 bits, multiply first, then divide. */
    int32_t mv = (int32_t)counts * 3300 / 4096;

    /* Better: add half the divisor first to round to nearest. */
    int32_t mv_rounded = ((int32_t)counts * 3300 + 4096 / 2) / 4096;

    printf("divide first: %ld mV\n", (long)mv_div_first);
    printf("16-bit:       %u mV\n", (unsigned)mv_16bit);
    printf("32-bit:       %ld mV\n", (long)mv);
    printf("rounded:      %ld mV\n", (long)mv_rounded);
    return 0;
}

Output:

divide first: 0 mV
16-bit:       46400 mV
32-bit:       1611 mV
rounded:      1611 mV

The exact answer is 1611.33 mV, so here rounding and truncating agree; try 2003 counts (1613.75 mV), where truncating gives 1613 and rounding gives 1614. Look at each line:

  • Divide first throws away everything: integer division truncates 2000 / 4096 to 0.
  • The 16-bit result wrapped around. 6,600,000 does not fit in 16 bits (maximum 65,535), and 6,600,000 mod 65,536 = 46,400. The cast here imitates what happens on a processor whose int is 16 bits wide, where the multiplication itself overflows.
  • 32-bit, multiply first keeps the precision; the largest possible intermediate, 4095 × 3300 = 13,513,500, fits easily in an int32_t (maximum about 2.1 billion).
  • Rounding: integer division always rounds towards zero. Adding half the divisor first rounds to the nearest whole number instead. (For negative numbers you would subtract it; check the sign.)

The general rules: multiply before you divide, make sure the intermediate cannot overflow, and decide how you want to round. Before writing a scaling line, work out the largest value any intermediate can reach.

Chaining conversions

Suppose an illustrative temperature sensor outputs 500 mV at 0 °C and rises by 10 mV per °C. In centidegrees:

temp_cdeg = (sensor_mv − 500) × 10

So 750 mV gives (750 − 500) × 10 = 2500, meaning 25.00 °C, and 430 mV gives −700, meaning −7.00 °C. Note that the result can be negative, so it must live in a signed type. Every step stays in integers.

Q formats: fractions in integers

Sometimes you need genuine fractions, such as a filter coefficient of 0.3 or a gain of 1.5. Q format fixed point stores a number multiplied by a power of two. In Q16.16, the stored integer is the value × 65,536 (2¹⁶): 16 bits for the whole part, 16 for the fraction.

1.5   → 1.5 × 65536   =  98304
2.25  → 2.25 × 65536  = 147456

Adding two Q16.16 numbers is ordinary integer addition. Multiplying needs care: the product has 32 fractional bits, so you multiply in 64 bits and shift right by 16:

(98304 × 147456) >> 16 = 14495514624 >> 16 = 221184  → 221184 / 65536 = 3.375

And 1.5 × 2.25 is indeed 3.375. Powers of two are used because shifting is very cheap on any processor. Another common choice, Q15, stores values between −1 and just under +1 in an int16_t, popular in audio and signal processing.

Fixed-point filters and the stuck-filter bug

The exponential filter from the noise lesson is easy to write in integers with α = 1/4: y += (x − y) / 4. But watch what happens when the filter approaches its target:

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

int main(void)
{
    int32_t target = 100;
    int32_t plain = 0;      /* filter state in whole units          */
    int32_t scaled = 0;     /* filter state in 1/16ths (4 extra bits) */

    for (int k = 1; k <= 30; k++) {
        plain  += (target - plain) / 4;              /* alpha = 1/4 */
        scaled += (target * 16 - scaled) / 4;
        if (k % 10 == 0) {
            printf("k=%2d  plain=%ld  scaled=%ld (= %ld.%02ld)\n", k,
                   (long)plain, (long)scaled,
                   (long)(scaled / 16), (long)(scaled % 16 * 100 / 16));
        }
    }
    return 0;
}

Output:

k=10  plain=93  scaled=1508 (= 94.25)
k=20  plain=97  scaled=1593 (= 99.56)
k=30  plain=97  scaled=1597 (= 99.81)

The plain filter gets stuck at 97: once the gap is less than 4, (100 − 97) / 4 truncates to 0 and nothing ever changes again. Keeping the filter state with 4 extra fractional bits (in sixteenths) lets it creep to within 0.2 of the target. The lesson generalises: keep extra fractional bits in any value that accumulates small changes, and only round when you output the result.

Project

Programming project: integer-only conversion

Write a C99 or Python program (in Python, use only // integer division and no floats) that converts 10-bit ADC readings (0 to 1023) with a 5000 mV reference into millivolts using only integers.

  1. Implement truncating and rounding versions, and compare both with the exact floating-point answer for every input from 0 to 1023. Report the largest error for each.
  2. Work out the largest intermediate value and state the smallest integer type that safely holds it.
  3. Implement an integer exponential filter with α = 1/8, with and without 3 extra fractional bits, and show where each settles for a constant input of 500.

This is a computer-only activity. No hardware is needed.

Deliverables

  • Source code with units in every variable name
  • The largest error of the truncating and rounding conversions
  • The largest intermediate value and chosen type, with reasoning
  • Settled values of both integer filters

Knowledge check

Check your understanding

  1. 1. In C integer arithmetic, what is 3000 / 4096 * 3300?
  2. 2. Why does counts * 3300 risk overflow on a processor with a 16-bit int?
  3. 3. What value represents 0.75 in Q16.16 format?
  4. 4. An integer filter y += (x − y) / 8 stops changing before it reaches the input. What is the best fix?
  5. 5. Why is temp_cdeg a better variable name than temp?

Go further