detecting multiplication of uint64_t integers overflow with C

前端 未结 5 1164
天涯浪人
天涯浪人 2021-02-07 08:11

Is there any efficient and portable way to check when multiplication operations with int64_t or uint64_t operands overflow in C?

For instance, for addition of uint64_t I

5条回答
  •  梦谈多话
    2021-02-07 08:41

    It might not detect exact overflows, but in general you can test the result of your multiplication on a logarithmic scale:

    if (log(UINT64_MAX-1) - log(a) - log(b) < 0) overflow_detected(); // subtracting 1 to allow some tolerance when the numbers are converted to double
    else prod = a * b;
    

    It depends if you really need to do multiplication up to exact UINT64_MAX, otherwise this a very portable and convenient way to check multiplications of large numbers.

提交回复
热议问题