【问题标题】:Java "x += y" and "x = x+y" yields different resultJava "x += y" 和 "x = x+y" 产生不同的结果
【发布时间】:2018-05-18 00:53:34
【问题描述】:

我想出了两个表达式来将位操作的值赋给变量,并注意到在这种情况下“x+=y”和“x=x+y”产生了不同的结果:

public void random () 
{
        int n =     43261596;
        System.out.println(Integer.toBinaryString(n));
        n = n + 0&1; //binary representation of n is 0
        //n += 0&1;  //result is the same as n
        System.out.println(Integer.toBinaryString(n));
}

我做了一些研究,发现“x+=y”和“x=x+y”不等价的唯一情况是操作类型不同时,但是在这种情况下,“n”是@的类型987654323@,而“0&1”应该是int的类型(根据这个问题Why does bitwise AND of two short values result in an int value in Java?

因为 Java 语言规范说非长整数运算的结果总是一个 int。)

所以我想知道为什么它会产生不同的结果。

【问题讨论】:

    标签: java casting bit-manipulation


    【解决方案1】:

    区别是operator precedence+ 优先于&,但& 优先于+=。所以你的操作转化为:

    n = (n + 0) & 1; // = n & 1 = 0 (when n is even)
    n += (0 & 1);    // = n + 0 = n
    

    【讨论】:

    【解决方案2】:

    运算符 & 的优先级低于 +。

    你实际写的是:

    n = ( n + 0 ) &1;
    

    我加了括号来澄清。

    由于 n 是偶数,因此该表达式的结果为零。

    【讨论】:

      【解决方案3】:

      在第一种情况下,n会先 0,然后 1

      n = n+0&1 -> n = (n + 0)&1 -> 0
      n+=0&1 ->n+=(0&1)->n
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多