【发布时间】: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