Avoiding overflow in integer multiplication followed by division

后端 未结 4 1700
失恋的感觉
失恋的感觉 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 09:09

    If the larger type is just 64 bits then the straight forward solution will most likely result in efficient code. On x86 CPUs any multiplication of two 32 bit numbers will give the overflow in another register. So if your compiler understands that, it can generate efficient code for Int64 result=(Int64)a*(Int64)b.

    I had the same problem in C#, and the compiler generated pretty good code. And C++ compilers typically create better code than the .net JIT.

    I recommend writing the code with the casts to the larger types and then inspect the generated assembly code to check if it's good.

提交回复
热议问题