"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What is the Purpose of the Pipe Equal (=) Operator in Programming?

What is the Purpose of the Pipe Equal (=) Operator in Programming?

Published on 2024-11-07
Browse:364

What is the Purpose of the Pipe Equal (=) Operator in Programming?

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 (1 

This allows the use of bitwise OR to add or remove flags. For instance:

int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // 001 | 010 = 011

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

Release Statement This article is reprinted at: 1729671437 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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