Avoiding overflow in integer multiplication followed by division

后端 未结 4 1701
失恋的感觉
失恋的感觉 2020-12-31 08:32

I have two integral variables a and b and a constant s resp. d. I need to calculate the value of (a*b)>>s

4条回答
  •  滥情空心
    2020-12-31 08:58

    If there isn't a larger type, you will either need to find a big-int style library, or deal with it manually, using long multiplication.

    For instance, assume a and b are 16-bit. Then you can rewrite them as a = (1<<8)*aH + aL, and b = (1<<8)*bH + bL (where all the individual components are 8-bit numbers). Then you know that the overall result will be:

    (a*b) = (1<<16)*aH*bH
          + (1<<8)*aH*bL
          + (1<<8)*aL*bH
          + aL*bL
    

    Each of these 4 components will fit a 16-bit register. You can now perform e.g. right-shifts on each of the individual components, being careful to deal with carries appropriately.

提交回复
热议问题