Java,威尔(低和高)>&燃气轮机&燃气轮机;1溢出?
我正在看Java1.8API。 在Java,威尔(低和高)>&燃气轮机&燃气轮机;1溢出?,java,overflow,Java,Overflow,我正在看Java1.8API。 在java.util.Arrays.binarySearch(int[]a,int-key)中,我找到了这段代码 int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; if (midVal < key) low
java.util.Arrays.binarySearch(int[]a,int-key)
中,我找到了这段代码
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
那么,这是否意味着逻辑右移将考虑溢出位 对于足够大的
low
和high
值,表达式将溢出是正确的。如果其中一个值为负值,则可能会得到不正确的结果
但是,在二进制搜索方法中不能得到负数,因为low
和high
都是数组的索引;它们必须是积极的。因此,加法的结果将只溢出到符号位;它不会产生进位
由于Java的
>>
运算符将在不带符号扩展的情况下移位符号位,因此即使对于两个整数.MAX_值
,也会得到正确的结果。本质上,>>
运算符允许您将第32位视为无符号存储的额外位,即使该位属于有符号类型。如果低+高
的结果溢出并变为负,则(低+高)/2和(低+高)>>1都不起作用
a>>1
保留原始文件的符号位,因此a
的负值将给出负值结果
a>>1
通过引入零符号位工作,因此任何a
的结果都不能为负
演示:
int low = 1;
int high = Integer.MAX_VALUE;
System.out.println(low + high); // This is negative
System.out.println((low + high) >>> 1); // This is positive, and the desired result.
System.out.println((low + high) >> 1); // This is negative
System.out.println((low + high) / 2); // This is negative
由于溢出,查找两个int
值的中间值很容易出错。有关适用于正值和负值的表达式,请参阅。代码将这些值视为32位无符号整数,两个31位有符号整数之和不能大于32位无符号整数,因此此操作不会溢出。注意:如果您使用>
,可能会出现问题。
int low = 1;
int high = Integer.MAX_VALUE;
System.out.println(low + high); // This is negative
System.out.println((low + high) >>> 1); // This is positive, and the desired result.
System.out.println((low + high) >> 1); // This is negative
System.out.println((low + high) / 2); // This is negative