Fixed-point rounding with a widened intermediate in C
A fixed-point representation stores an integer whose scale is understood by the application. Multiplication combines two scales, so the result must be brought back to the required one. The intermediate can exceed the original storage type even when the final result fits. Widening after multiplication would be too late if the original operation overflows.
The contract
For a small decimal scale of 100, the following example rounds a product to the nearest scaled unit with ties away from zero. C integer division truncates toward zero. Adding or subtracting half the divisor before division implements the chosen tie rule within the specified bounds. A power-of-two scale has similar reasoning but signed shifts are not a substitute for a stated rounding policy.
A small executable example
#include <stdint.h>
#include <assert.h>
#include <stdio.h>
static int32_t mul_scale100(int16_t a, int16_t b) {
int64_t p = (int64_t)a * b;
p += p < 0 ? -50 : 50;
return (int32_t)(p / 100);
}
int main(void) {
assert(mul_scale100(125, 200) == 250);
assert(mul_scale100(-125, 2) == -3);
assert(mul_scale100(125, 2) == 3);
assert(mul_scale100(0, -100) == 0);
puts("scaled products verified");
}
scaled products verified
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
What the example does not establish
Both inputs are int16_t so their largest magnitude product plus the rounding adjustment fits int64_t, and the divided result fits int32_t. A general version accepting larger inputs needs a new range proof and perhaps a checked multiplication. Saturation, rejection and rounding are distinct policies; do not silently truncate to the destination type.
Checks to add in your own project
Add tests immediately below, at, and above half a scaled unit, for both signs. Compare against an independent reference calculation using exact integer arithmetic when practical. Measure the generated division and multiplication on the chosen core if the function is performance-sensitive. Host execution confirms the stated sample results but not the timing cost on a microcontroller.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.