[英]Why does incrementing a Java int eventually result in a negative number?
I was trying to check different inputs and creating infinite loops in java and I found that once the int
is getting incremented over the maximum limit it turns in to negative -2147482958
. 我试图检查不同的输入并在java中创建无限循环,我发现一旦int
增加超过最大限制,它将转为负-2147482958
。 I am just increasing the int in infinite loop... 我只是在无限循环中增加int ...
public static void infiniteLoop(){
for(int i=0;i>-1;i++){
i = i + 1000;
System.out.println(i);
}
}
The last to value gets printed out is, 打印出来的最后一个值是,
2147483337
-2147482958
Now, Why does it goes to negative? 现在,为什么会出现负面影响?
Why does it goes to negative? 它为什么会消极?
Because that is what is specified to happen in Java when an int
calculation overflows. 因为当int
计算溢出时,这就是Java中指定的内容。
"If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values." “如果整数加法溢出,则结果是数学和的低阶位,如某些足够大的二进制补码格式所示。如果发生溢出,那么结果的符号与符号的符号不同两个操作数值的数学和。“
(This doesn't explicitly say that overflow always gives a negative number. And it doesn't always. But if you apply the rule, it does explain why incrementing Integer.MAX_VALUE
by +1
gives you Integer.MIN_VALUE
...) (这并没有明确地说溢出总是给出一个负数。并且它并不总是。但是如果你应用规则,它确实解释了为什么递增Integer.MAX_VALUE
乘以+1
给你Integer.MIN_VALUE
...)
According to the documentation: 根据文件:
The int data type is a 32-bit signed two's complement integer. int数据类型是32位带符号的二进制补码整数。 It has a minimum value of -2,147,483,648 (0x80000000) and a maximum value of 2,147,483,647 (0x7FFFFFFF) (inclusive) 它的最小值为-2,147,483,648(0x80000000),最大值为2,147,483,647(0x7FFFFFFF)(含)
So when you add one to an integer's max value: 因此,当您将一个加到整数的最大值时:
0x7FFFFFFF + 0x00000001 = 0x80000000 (-2,147,483,648) 0x7FFFFFFF + 0x00000001 = 0x80000000(-2,147,483,648)
Because when the value of an int reaches Integer.MAX_VALUE , incrementing it causes overflow and hence wraps around to Integer.MIN_VALUE . 因为当int的值达到Integer.MAX_VALUE时 ,递增它会导致溢出 ,因此会回绕到Integer.MIN_VALUE 。
To use larger integers, use a long instead which has 64 bits . 要使用更大的整数,请使用long而不是64位 。
Because int
ranges from -2,147,483,648 to 2,147,483,647. 因为int
范围从-2,147,483,648到2,147,483,647。 Hence,once it reaches it upper limit, it overflows and starts from the negative. 因此,一旦达到上限,它就会溢出并从负面开始。
The int data type is a 32-bit signed two's complement integer. int数据类型是32位带符号的二进制补码整数。 It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive) 它的最小值为-2,147,483,648,最大值为2,147,483,647(含)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.