How can I detect integer overflow on 32 bits int?

前端 未结 5 1309
逝去的感伤
逝去的感伤 2020-12-03 06:33

I know such topic was asked several times, but my question is about overflow on full 32 bits of int. For example:

  11111111111111111111111         


        
5条回答
  •  北海茫月
    2020-12-03 07:03

    The most intuitive method I can think of: calculate the sum (or difference) as a long, then convert that sum to an int and see if its value has changed.

    long longSum = (long) a + b;
    int sum = (int) longSum;
    if (sum == longSum) {
        // sum contains the correct result
    } else {
        // overflow/underflow
    }
    

    Remember that on modern 64 bit processors, working with longs is no less efficient than working with ints (the opposite may be true). So if you have a choice between checking for overflows or using longs, go for the latter.

提交回复
热议问题