我想弄清楚 >>= 和 >>>= 之间的区别。我明白他们在做什么,但我不明白其中的区别。
下面的输出为 38 152 38 152。
按位分配 >>>= 似乎与 >>= 完全相同。
public static void main(String[] args)
{
int c = 153;
System.out.print((c >>= 2));
System.out.print((c <<= 2));
System.out.print((c >>>= 2));
System.out.print((c <<= 2));
}
阅读更多关于 Bitwise and Bit Shift Operators 的信息
>> Signed right shift
>>> Unsigned right shift
位模式由左侧操作数给出,要移动的位置数由右侧操作数给出。无符号右移运算符 >>>
将零移到最左边的位置,
而在>>
之后最左边的位置取决于符号扩展。
简单来说 >>>
总是将零移到最左边的位置而>>
根据数字的符号移动,即 1 表示负数,0 表示正数。
例如尝试使用负数。
int c = -153;
System.out.printf("%32s%n",Integer.toBinaryString(c >>= 2));
System.out.printf("%32s%n",Integer.toBinaryString(c <<= 2));
System.out.printf("%32s%n",Integer.toBinaryString(c >>>= 2));
System.out.println(Integer.toBinaryString(c <<= 2));
c = 153;
System.out.printf("%32s%n",Integer.toBinaryString(c >>= 2));
System.out.printf("%32s%n",Integer.toBinaryString(c <<= 2));
System.out.printf("%32s%n",Integer.toBinaryString(c >>>= 2));
System.out.printf("%32s%n",Integer.toBinaryString(c <<= 2));
输出:
11111111111111111111111111011001
11111111111111111111111101100100
111111111111111111111111011001
11111111111111111111111101100100
100110
10011000
100110
10011000