Fix changeUIntScale to be stable

This commit is contained in:
Stephan Hadinger 2021-12-23 12:48:12 +01:00
parent 7bf6e5a773
commit 7c064f6fc8
1 changed files with 13 additions and 2 deletions

View File

@ -407,8 +407,19 @@ uint16_t changeUIntScale(uint16_t inum, uint16_t ifrom_min, uint16_t ifrom_max,
to_max = ito_min;
}
uint32_t numerator = (num - from_min) * (to_max - to_min + 1);
uint32_t result = numerator / (from_max - from_min) + to_min;
// short-cut if limits to avoid rounding errors
if (num == from_min) return to_min;
if (num == from_max) return to_max;
uint32_t result;
if ((num - from_min) < 0x8000L) { // no overflow possible
uint32_t numerator = ((num - from_min) * 2 + 1) * (to_max - to_min + 1);
result = numerator / ((from_max - from_min + 1) * 2) + to_min;
} else { // no pre-rounding since it might create an overflow
uint32_t numerator = (num - from_min) * (to_max - to_min + 1);
result = numerator / (from_max - from_min) + to_min;
}
return (uint32_t) (result > to_max ? to_max : (result < to_min ? to_min : result));
}