Home > Java > javaTutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-23 16:55:01
Original
943 people have browsed it

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;
Copy after login

This operation is equivalent to:

notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;
Copy after login

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 << 1)
DEFAULT_LIGHTS = 4 (1 << 2)
Copy after login

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

int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // 001 | 010 = 011
Copy after login

Adding another flag:

myFlags |= DEFAULT_LIGHTS;
Copy after login

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;
Copy after login

If the result is non-zero, the flag is set.

The above is the detailed content of What is the Purpose of the Pipe Equal (=) Operator in Programming?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!