“|="是什么意思?意思?(管道等于运算符) [英] What does "|=" mean? (pipe equal operator)
问题描述
我尝试使用 Google 搜索和 StackOverflow 进行搜索,但没有显示任何结果.我在开源库代码中看到过这个:
I tried searching using Google Search and Stack Overflow, but it didn't show up any results. I have seen this in opensource library code:
Notification notification = new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
|="(管道等于运算符
)是什么意思?
What does "|=" ( pipe equal operator
) mean?
推荐答案
|=
读取方式与 +=
相同.
|=
reads the same way as +=
.
notification.defaults |= Notification.DEFAULT_SOUND;
与
notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;
其中 |
是按位 OR 运算符.
where |
is the bit-wise OR operator.
在此处引用了所有运算符.
使用按位运算符是因为,这些常量经常使 int 能够携带标志.
A bit-wise operator is used because, as is frequent, those constants enable an int to carry flags.
如果您看看这些常量,你会发现它们是 2 的幂:
If you look at those constants, you'll see that they're in powers of two :
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
所以你可以使用按位或来添加标志
So you can use bit-wise OR to add flags
int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // same as 001 | 010, producing 011
所以
myFlags |= DEFAULT_LIGHTS;
只是意味着我们添加了一个标志.
simply means we add a flag.
并且对称地,我们测试使用 &
设置的标志:
And symmetrically, we test a flag is set using &
:
boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;
这篇关于“|="是什么意思?意思?(管道等于运算符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!