Replace division by a constant with a reciprocal multiply on Cortex-M0
Divide a 16-bit value by 10 on Cortex-M0 with one 32-bit multiply and a shift, exact for every input, instead of a slow library division call.
Cortex-M0 has no divide instruction, so x / 10 normally becomes a call into the compiler's runtime library, __aeabi_uidiv, which loops for many cycles. For a 16-bit input and a constant divisor you can do it with the 32-bit multiply the core does have, followed by a shift. This is a narrower trick than the general multiply-and-shift one, and it is built around what this core can do.
#include <stdint.h>
#include <stdio.h>
static inline uint16_t div10(uint16_t x) {
return (uint16_t)(((uint32_t)x * 52429u) >> 19);
}
int main(void) {
printf("%u %u\n", div10(40000), div10(65535));
return 0;
}4000 6553The constant 52429 is 2 to the power 19 divided by 10, rounded up, which is a hair above one tenth: 52429 over 524288 is about 0.1000004. The product of any 16-bit x and 52429 is at most 65535 times 52429, about 3.4 billion, and that fits in 32 bits, so a single MULS is enough, with no 64-bit result that M0 cannot produce.
The rounding error is what limits the range. At 65535 the extra amount is about 0.025, smaller than the 0.1 gap by which a remainder of 9 sits below the next whole number, so the result is exact for every 16-bit input. A wider input would break it, and then you need a bigger shift and a 64-bit multiply, which this core lacks.
Keep the remainder with x - 10 * q. The absence of a hardware divider is stated in the Cortex-M0 Devices Generic User Guide. Measure your own build: GCC may already do this for you at higher optimisation levels on cores that have a long multiply.