[JAVA] Cases that are often forgotten due to integer overflow

For programmers, when calculating, regarding overflow, I think I'm always careful, I will briefly summarize the cases that are often forgotten.

This article is a gaiden content picked up from the following contents.

1. Prerequisites to keep things simple

To keep things simple, we'll assume a 32-bit signed integer type. Regarding the contents of this time, if it is a signed integer type with fixed precision, Other sizes should also apply.

In Java, C #, C / C ++ Think of int, Int32, int32, etc. (In C / C ++, it is assumed that the int type is a 32-bit processing system.)

2. Overflow that is often forgotten in multiplication

Multiplication of large numbers is easy to overflow It's not the main subject because I think you can imagine it right away.

The main subject is the following cases.

int a = Int32.MinValue;
int b = -1;

int answer = a * b;
int a = Integer.MIN_VALUE;
int b = -1;

int answer = a * b;
int a = INT_MIN;
int b = -1;

int answer = a * b;

ʻA contains -2147483648, Multiplying by -1 exceeds 2147483647, which can be represented by a 32-bit signed integer. In my environment, the result of each ʻanswer variable is -2147483648. For C #, if you set it to checked, an OverFlowException will occur.

If the value can be evaluated at build or compile time, At that point, an overflow may be detected.

3. Overflow that is often forgotten in division

In integer division, if overflow does not occur, In some cases, it may be misunderstood, but it may overflow properly (?!).

int a = Int32.MinValue;
int b = -1;

int answer = a / b;
int a = Integer.MIN_VALUE;
int b = -1;

int answer = a / b;
int a = INT_MIN;
int b = -1;

int answer = a / b;

Similar to multiplication, but Dividing by -1 is the same as multiplying by -1, so It exceeds 2147483647, which can be represented by a 32-bit signed integer. In my environment, in Java, the result of the ʻanswer variable is -2147483648. In C ++, an integer overflow exception occurred. ** For C #, I get an OverFlowException regardless of whether it is checked` or not. ** **

3. Summary

Recommended Posts

Cases that are often forgotten due to integer overflow
[Updated from time to time] Links that are indebted
[Java] The problem that uploaded images are not updated due to the influence of cache