简体   繁体   English

如何否定一个值与java [Integer.Min_Value]中的值相同

[英]How negating a value is same as the value in java [Integer.Min_Value]

How can these values be same in java? 这些值如何在java中相同?

-Integer.MIN_VALUE == Integer.MIN_VALUE

values are: 价值观是:

-2147483648 : -2147483648

i tried comparing it and returns true [Amazing!] 我试着比较它并返回真实[惊人!]

Yes, that's expected behaviour. 是的,这是预期的行为。 The range of int is -2147483648 to +2147483647. int的范围是-2147483648到+2147483647。

From the JLS section 15.15.4 (emphasis mine): JLS第15.15.4节 (强调我的):

For integer values, negation is the same as subtraction from zero. 对于整数值,否定与从零减去相同。 The Java programming language uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number . Java编程语言对整数使用二进制补码表示,并且二进制补码值的范围不对称, 因此否定最大负数intlong导致相同的最大负数 Overflow occurs in this case, but no exception is thrown. 在这种情况下会发生溢出,但不会抛出异常。 For all integer values x , -x equals (~x)+1 . 对于所有整数值x-x等于(~x)+1

~Integer.MIN_VALUE is Integer.MAX_VALUE ... and when you add one, it overlows to Integer.MIN_VALUE . ~Integer.MIN_VALUEInteger.MAX_VALUE ...当你添加一个时,它会溢出到Integer.MIN_VALUE

This is why when you implement a reversing comparator, you mustn't do this: 这就是为什么当你实现一个反转比较器时,你不能这样做:

// BAD CODE!
public int compare(T x, T y) {
    return -originalComparator.compare(x, y);
}

Instead, use this: 相反,使用这个:

// This is fine, assuming the comparator obeys its contract
public int compare(T x, T y) {
    return originalComparator.compare(y, x));
}

Look at the below code: 看下面的代码:

System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);
System.out.println(-Integer.MIN_VALUE);

The minimum value for integer is -2147483648 , and when you take a negation for this, it becomes 2147483648 , which is 1 greater than Integer.MAX_VALUE , so it goes out of range, and moves towards the other end, and become -2147483648 整数的最小值是-2147483648 ,当你取消它时,它变为2147483648 ,比Integer.MAX_VALUE 1 ,因此它超出范围,并向另一端移动,变为-2147483648

Java uses two's complement arithmetic, which means negating a value is the same as flipping its bits and adding 1. Java使用二进制补码算法,这意味着否定一个值与翻转其位并添加1相同。

But what about the number with bit pattern 100..00? 但是比特模式100..00的数字怎么样? When you flip its bits you get 011..11, and when you add 1 you get 100..00, the same number you started with! 当你翻转它的位时你得到011..11,当你加1时你得到100..00,你开始时的数字相同!

For a range of other reasons this number is the lowest integer that can be represented, ie Integer.MIN_VALUE. 由于一系列其他原因,此数字是可以表示的最小整数,即Integer.MIN_VALUE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM