【问题标题】:Difference between >>= and >>>= [duplicate]>>= 和 >>>= 之间的区别 [重复]
【发布时间】:2014-08-16 13:47:41
【问题描述】:

我正在尝试找出 >>= 和 >>>= 之间的区别。我明白他们在做什么,但我不明白他们的区别。 下面的输出为 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));
}

【问题讨论】:

标签: java


【解决方案1】:

阅读更多关于Bitwise and Bit Shift Operators

>>      Signed right shift
>>>     Unsigned right shift

位模式由左侧操作数给出,而要移位的位置数由右侧操作数给出。无符号右移运算符&gt;&gt;&gt; 将一个移到最左边的位置

&gt;&gt; 之后最左边的位置取决于符号扩展。

简单来说&gt;&gt;&gt;总是移到最左边的位置&gt;&gt;根据数字的符号进行移动,即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

【讨论】:

  • 如果不是使用System.out.println(x)(对于某些x),而是使用System.out.printf("%32d%n", x) 来使它们正确对齐,可能会更清楚,尽管我不确定是否会这样做。跨度>
  • @DavidConrad 谢谢,但我也想以二进制格式显示它以使其更清晰。我已经在我的帖子中更新了它。
  • 哦,是的,对不起,我是想写%32s。脑放屁。
猜你喜欢
  • 2011-04-08
  • 2012-11-24
  • 2013-06-05
  • 2021-09-29
  • 2020-05-27
  • 2016-03-23
  • 2012-08-11
  • 2012-11-24
  • 2017-07-19
相关资源
最近更新 更多