detecting multiplication of uint64_t integers overflow with C

前端 未结 5 1159
天涯浪人
天涯浪人 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:42

    If you want to avoid division as in Ambroz' answer:

    First you have to see that the smaller of the two numbers, say a, is less than 232, otherwise the result will overflow anyhow. Let b be decomposed into the two 32 bit words that is b = c 232 + d.

    The computation then is not so difficult, I find:

    uint64_t mult_with_overflow_check(uint64_t a, uint64_t b) {
      if (a > b) return mult_with_overflow_check(b, a);
      if (a > UINT32_MAX) overflow();
      uint32_t c = b >> 32;
      uint32_t d = UINT32_MAX & b;
      uint64_t r = a * c;
      uint64_t s = a * d;
      if (r > UINT32_MAX) overflow();
      r <<= 32;
      return addition_with_overflow_check(s, r);
    }
    

    so this are two multiplications, two shifts, some additions and condition checks. This could be more efficient than the division because e.g the two multiplications can be pipelined in paralle. You'd have to benchmark to see what works better for you.

提交回复
热议问题