mirror of https://github.com/arendst/Tasmota.git
Merge pull request #14157 from s-hadinger/better_changeUIntScale
Fix changeUIntScale to be stable
This commit is contained in:
commit
8374ded1d4
|
@ -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));
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue