Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "|=" mean? (pipe equal operator)

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?

like image 769
wtsang02 Avatar asked Jan 12 '13 16:01

wtsang02


People also ask

What is the meaning of |= operator?

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.

What is |= in C programming?

|= 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.

What does |= mean in Python?

|= 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.

What does |= mean in C++?

|= just assigns the bitwise OR of a variable with another to the one on the LHS.


1 Answers

|= 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; 
like image 118
Denys Séguret Avatar answered Oct 03 '22 06:10

Denys Séguret