Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to judge integer data overflow
How to judge integer data overflow
Integer overflow, how to judge the set of integer overflow

There are two kinds of integer arithmetic operations in C language, signed operation and unsigned operation. In unsigned operations, there is no sign bit, so there is no concept of overflow.

All unsigned operations are modulo 2 to the n power. If one operand of an arithmetic operator is a signed book and the other is an unsigned number, then there is a signed number.

Will be converted to an unsigned number (meaning that a small range is always converted to a large range), then overflow will not occur. However, when both operands are signed numbers.

Overflow may occur. The result of overflow is uncertain. When the operation result overflows, any assumption is unsafe.

For example, if A and B are two non-negative integer variables (signed), we need to check whether a+b overflows. One way to take it for granted is:

if(a+b & lt; 0)

Overflow;

In fact, in the real world, this does not work properly. When a+b does overflow, all assumptions about the result are unreliable. For example, in some cases

In the cpu of the machine, the addition operation will set an internal register to four states: positive, negative, zero and overflow. On this machine, the C compiler has every reason to realize the above contents.

For example, so that a+b returns not a negative number, but the overflow status of this memory register. Obviously, if's judgment will fail.

The correct method is to convert both a and b into unsigned integers:

If ((unsigned) a+(unsigned) b & gtINT_MAX)

Overflow;

Here the value of int_max is the maximum value of a signed integer. It is a predefined constant in the general compiler. ANSI C defines INT_MAX in limits, and the value is

3 1 power of 2-1.

Another feasible method that does not require unsigned arithmetic operation is:

If (a & gtINT_MAX-b)

Overflow;

PS: The most significant bit (3 1 bit) of the signed number is the sign bit, and when the most significant bit is 0, it means positive, and when it is 1, it means negative. During the operation, the sign bit does not participate in the operation, but if two numbers are added, 30 bits need to input 1, which means overflow.