Path: csiph.com!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: How to avoid an overflow during multiplication? Date: Sun, 02 Jan 2022 09:08:24 -0800 Organization: A noiseless patient Spider Lines: 19 Message-ID: <86wnjixdyv.fsf@linuxsc.com> References: <86a6ggzl16.fsf@linuxsc.com> <864k6oz11s.fsf@linuxsc.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="91c51c7bf9602b3ccc1d4ef284765d17"; logging-data="5448"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/A9qtC1ppvDrnAbKOkdppZWD2mrpBQ330=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:3RvCZ0P5TdfB3LARuMk1pCqiuSM= sha1:HZr2ERZOsBwfrrsaZmM2ZPzpX0g= Xref: csiph.com comp.lang.c:164223 Tim Rentsch writes: [...] > One further idea.. after posting it occurred to me that there is > a technique that is guaranteed to give the right answer as long > as the result fits in 32 bits: > > uint32_t > ticks2time( uint32_t ticks, uint16_t tempo, uint16_t scale ){ > uint32_t th = ticks >> 16; > uint32_t th_tempo = th * tempo; > uint32_t tl = (uint16_t) ticks; > return > (th_tempo / scale << 16) + > ((th_tempo % scale << 16) + tl*tempo) / scale; > } I must recant this earlier comment. Haste makes bugs.