...
By using the BigInteger class there is no chance to overflow (see section on BigInteger class) but the performance is degraded so it should be used only on really large operations
\\\\
Subtraction
Care must be taken in subtraction operations as well as these can overflow as well.
...
Code Block | ||
---|---|---|
| ||
int a,b,result; long temp = (long)a-(long)b; if(long < Integer.MIN_VALUE || long > Integer.MAX_VALUE) throw ArithmeticException; else result = (int) temp; |
\\\\
Multiplication
This noncompliant code example, can result in a signed integer overflow during the multiplication of the signed operands a and b. If this behaviour is unanticipated, the resulting value may lead to undefined behaviour
Noncompliant Code Example
Code Block | ||
---|---|---|
| ||
int a,b,result //do stuff result = a*b;//May result in overflow |
\\\\
Compliant Code Example
Since in this platform the size of type long (64 bits) is twice the size of type int (32 bits) we should perform the multiplication in terms of long and if the product is in the integer range we downcast the result to int
...
Code Block | ||
---|---|---|
| ||
int a,b,result result = a/b; |
\\\\
Compliant Code Example
Code Block | ||
---|---|---|
| ||
if(a == Integer.MIN_VALUE && b == -1) throw ArithmeticException;//May be Integer.MIN_VALUE again???? else result = a/b;//safe operation |
...
Although we can not have undefined behaviour in Java we still have to ensure that we get the correct results. So we should
explicitly check for ranges
Code Block | ||
---|---|---|
| ||
if(shift_value > 31 or shift_value <0)if(shift_value > 31 or shift_value <0) throw ArithmeticException; else int val = 2 << shift_value; throw ArithmeticException; else int val = 2 << shift_value; |
Unsigned Right shifting >>>
It is identical to the right-shift operator if the shifted value is positive. If it is negative the sign value can
change because the left-operand high-order bit is not retained and the sign value can change; Excerpt
from JLS:
"if n is negative, the result is equal to that of the expression (n>>s)(2<<~s) if the type of the left-hand operand is int, and to the result of the expression (n>>s)(2L<<~s) if the type of the left-hand operand is long. The added term (2<<~s) or (2L<<~s) cancels out the propagated sign bit. (Note that, because of the implicit masking of the right-hand operand of a shift operator, ~s as a shift distance is equivalent to 31-s when shifting an int value and to 63-s when shifting a longvalue.)"
For example: -32 >>> 2 = (-32 >> 2 ) + ( 2 << ~2 ) = 1073741816
Operations Requiring Really Long Numbers
...