use >>>= with short# Java - 爪哇娇娃
r*r
1 楼
在下面的程序中,对short类型s,无符号右移并赋值(见最后引用,这个操作中间经历
int, right shift, truncation 3个过程)。难道结果不应该还是short类型吗?可是
结果-1是int,32位.没想明白,很不爽。谁能解惑,指点迷津?
//: operators/URShift.java
// Test of unsigned right shift.
//import static net.mindview.util.Print.*;
public class URShift {
public static void main(String[] args) {
short s = -1;
System.out.println(Integer.toBinaryString(s));
System.out.println(Integer.toBinaryString(s>>>10) + ": s>>>10");
s >>>= 10;
System.out.println(Integer.toBinaryString(s));
}
} /* Output:
11111111111111111111111111111111
1111111111111111111111: s>>>10
11111111111111111111111111111111
*///:~
---------The following are quoted from <>-----
"If you use it with byte or short, you don't get the correct results.
Instead, these are promoted to int and right shifted, but then truncated as
they are assigned back into their variables, so you get -1 in those cases."
int, right shift, truncation 3个过程)。难道结果不应该还是short类型吗?可是
结果-1是int,32位.没想明白,很不爽。谁能解惑,指点迷津?
//: operators/URShift.java
// Test of unsigned right shift.
//import static net.mindview.util.Print.*;
public class URShift {
public static void main(String[] args) {
short s = -1;
System.out.println(Integer.toBinaryString(s));
System.out.println(Integer.toBinaryString(s>>>10) + ": s>>>10");
s >>>= 10;
System.out.println(Integer.toBinaryString(s));
}
} /* Output:
11111111111111111111111111111111
1111111111111111111111: s>>>10
11111111111111111111111111111111
*///:~
---------The following are quoted from <
"If you use it with byte or short, you don't get the correct results.
Instead, these are promoted to int and right shifted, but then truncated as
they are assigned back into their variables, so you get -1 in those cases."