What is the Pipe Equal Operator (=)?
Developers who have encountered the pipe equal operator (|=) in open-source library code may wonder about its meaning. This operator, often mistaken for a logic assignment, holds a significant bitwise OR operation.
Understanding Bitwise OR
The pipe equal operator |= works identically to =. In the code below, the |= operator combines the original value of defaults with the constant DEFAULT_SOUND:
notification.defaults |= Notification.DEFAULT_SOUND;
This operation is equivalent to:
notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;
where | denotes the bitwise OR operator.
Bitwise OR in Constant Masks
In the provided example, the constants DEFAULT_SOUND, DEFAULT_VIBRATE, and DEFAULT_LIGHTS are powers of two:
DEFAULT_SOUND = 1 DEFAULT_VIBRATE = 2 (1This allows the use of bitwise OR to add or remove flags. For instance:
int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // 001 | 010 = 011Adding another flag:
myFlags |= DEFAULT_LIGHTS;simply appends a new flag.
Testing Flag Presence
The bitwise AND operator (&) tests for the presence of a flag:
boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;If the result is non-zero, the flag is set.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3