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?
The bitwise OR assignment operator ( |= ) uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable.
|= is shorthand for doing an OR operation and assignment. For example,, x |= 3 is equivalent to x = x | 3 . You can also use other operators ( +, -, *, & , etc) in this manner as well.
|= on Booleans The Python |= operator when applied to two Boolean values A and B performs the logical OR operation A | B and assigns the result to the first operand A . As a result, operand A is False if both A and B are False and True otherwise.
|= just assigns the bitwise OR of a variable with another to the one on the LHS.
|=
reads the same way as +=
.
notification.defaults |= Notification.DEFAULT_SOUND;
is the same as
notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;
where |
is the bit-wise OR operator.
All operators are referenced here.
A bit-wise operator is used because, as is frequent, those constants enable an int to carry flags.
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
so
myFlags |= DEFAULT_LIGHTS;
simply means we add a flag.
And symmetrically, we test a flag is set using &
:
boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With