你可以看看这些位.使用
two’s complement表示法,-4和-5的位,为简洁起见仅显示最后8位:
-4: 1111 1100
-5: 1111 1011
位移到右侧2位,带符号扩展:
-4 >> 2: 1111 1111 (-1)
-5 >> 2: 1111 1110 (-2)
通常,您会想到>>>不使用符号扩展,这是真的,但在这种情况下:
r >>>= 2;
…对于使用二进制数字提升的位移操作,值r被提升为int,但是复合赋值运算符将返回值转换回字节,并且移入的零“消失”.
byte r = -5; // 1111 1100
r >>>= -2; // promoted to int: 11111111 11111111 11111111 11111010
// bit shift: 00111111 11111111 11111111 11111110
// cast back to byte: 11111110 (-2)
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
也就是说,在这种情况下,位移的结果被转换回字节.
当r的值为-4时,发生相同的回送到字节操作.
请注意,如果未完成赋值部分,那么您将看不到相同的答案,因为它不会将结果强制转换回字节:
System.out.println(r >>> 2);
然后你会看到:
1073741822