Che*_*Xie 5 java casting bit-manipulation
我想出了两个表达式来将位操作赋值给变量,并注意到"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));
}
Run Code Online (Sandbox Code Playgroud)
我做了一些研究,发现唯一的情况是"x + = y"和"x = x + y"不等同于当操作类型不相同时,但是在这种情况下,"n"是类型的int,并且"0&1" "应该是一种类型int(根据这个问题为什么两个短值的按位AND会导致Java中的int值?:
因为Java语言规范说非长整数运算的结果总是int.)
所以我想知道它为什么产生不同的结果.
shm*_*sel 13
差异是运算符优先级.+优先&,但&优先+=.所以你的操作转化为:
n = (n + 0) & 1; // = n & 1 = 0 (when n is even)
n += (0 & 1); // = n + 0 = n
Run Code Online (Sandbox Code Playgroud)
运算符&的优先级低于+.
你实际写的是:
n = ( n + 0 ) &1;
Run Code Online (Sandbox Code Playgroud)
我添加了括号来澄清.
由于n是偶数,因此该表达式的结果为零.