Skip to content

Commit fb5334d

Browse files
nordic-krchnashif
authored andcommitted
sys: time_units: Increase range of z_tmcvt
Avoid result overflow due to intermediate product overflow. Algorithm was multiplying input value by target frequency before dividing it by source frequency. If target frequency was high (e.g. conversion to nanoseconds) it could easily lead to overflow even though final result would not overflow. Adjusting algorithm to avoid that. Note, that typically this code is resolved at compile time so it will not impact performance as long as it can be resolved. Signed-off-by: Krzysztof Chruscinski <[email protected]>
1 parent e2d67d6 commit fb5334d

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

include/sys/time_units.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ static TIME_CONSTEXPR ALWAYS_INLINE uint64_t z_tmcvt(uint64_t t, uint32_t from_h
132132
if (result32) {
133133
return (uint32_t)((t * to_hz + off) / from_hz);
134134
} else {
135-
return (t * to_hz + off) / from_hz;
135+
return (t / from_hz) * to_hz + ((t % from_hz) * to_hz + off) / from_hz;
136136
}
137137
}
138138
}

0 commit comments

Comments
 (0)