我尝试使用谷歌搜索和堆栈溢出搜索,但没有显示任何结果。我在开源库代码中看到过:
Notification notification = new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
“|=”(管道相等运算符)是什么意思?
我尝试使用谷歌搜索和堆栈溢出搜索,但没有显示任何结果。我在开源库代码中看到过:
Notification notification = new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
“|=”(管道相等运算符)是什么意思?
当前回答
|是位或操作符,它像+=一样被应用。
其他回答
|=和+=读起来是一样的。
notification.defaults |= Notification.DEFAULT_SOUND;
和
notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;
其中|是按位的OR运算符。
这里引用了所有的运算符。
之所以使用逐位操作符,是因为通常情况下,这些常量使整型对象可以带位。
如果你观察这些常数,你会发现它们是2的幂:
public static final int DEFAULT_SOUND = 1;
public static final int DEFAULT_VIBRATE = 2; // is the same than 1<<1 or 10 in binary
public static final int DEFAULT_LIGHTS = 4; // is the same than 1<<2 or 100 in binary
因此,您可以使用位或来添加标志
int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // same as 001 | 010, producing 011
so
myFlags |= DEFAULT_LIGHTS;
简单地说就是我们添加了一个标志。
对称地,我们使用&来测试标志的设置:
boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;
它是这个的缩写:
notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;
|是位或。
|是位或操作符,它像+=一样被应用。
你的问题已经有了充分的答案。但我的回答可能会帮助你更多地了解|=一类二进制运算符。
我正在为位操作符写表: 以下是有效的:
----------------------------------------------------------------------------------------
Operator Description Example
----------------------------------------------------------------------------------------
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
----------------------------------------------------------------------------------------
注意所有操作符都是二进制操作符。
另外注意:(对于以下几点,我想补充我的答案)
>>>是Java中的位运算符,称为Unsigned shift 但是>>>=不是Java中的运算符。> > > =操作符 ~是按位的补位,0到1和1到0(一元运算符),但~=不是运算符。 此外,!调用逻辑NOT运算符,但是!=检查两个操作数的值是否相等,如果值不相等则condition为true。(A != B)是正确的。其中A=!B表示如果B为真,则A为假(如果B为假,则A为真)。
边注:|不叫管道,而是叫OR,管道是shell术语,将一个进程转移到下一个进程。
备注:||=不存在。(逻辑或) 你可以使用
y= y || expr; // expr is NOT evaluated if y==true
or
y = expr ? true : y; // expr is always evaluated.