Mail Archives: djgpp/1997/08/04/06:23:31
Jeff Weeks wrote:
> My multiply function overflows everytime, and it's obvious why.
> Here's what I do:
>
> (x * y) >> 16;
Yes, that obviously won't work. My suggestion is to divide it
into integer and fractional parts.
Split x into xh (high 16 bits) and xl (low 16 bits), similarly
with y into yh and yl. So x = (xh<<16) + xl, etc. Then:
result = ((xh*yh)<<16) + (xh*yl + xl*yh) + ((xl*yl)>>16)
You'll lose the top 16 bits of xh*yh, of course, but that's
inevitable, the same way as you lose the bottom 16 bits. If
you're really concerned you could think about rounding the bottom
bit, but it probably doesn't matter too much.
Oh, and note this works for unsigned but will probably do all
sorts of odd things with signed...
HTH,
Chris C
- Raw text -