2

can anyone explain what this |= means ? Like in here:

   noti.flags |= Notification.FLAG_AUTO_CANCEL;
Dodi
  • 2,201
  • 4
  • 30
  • 39

4 Answers4

4

It's a short representation of the statement:

noti.flags = noti.flags | Notification.FLAG_AUTO_CANCEL;
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
2

It's a Bitwise OR operator used as assignment

noti.flags |= Notification.FLAG_AUTO_CANCEL;

is the same of

noti.flags = noti.flags | Notification.FLAG_AUTO_CANCEL
Oscerd
  • 1,616
  • 11
  • 14
2

It's the assignment version of the Bitwise Or operator, ie:

 noti.flags = noti.flags | Notification.FLAG_AUTO_CANCEL;

The bitwise or does an inclusive bitwise OR operation:

10110 bitwise or
01100
-----------------
11110

From the source code:

Bit to be bitwise-ored into the flags field that should be set if the notification should be canceled when it is clicked by the user.

public static final int FLAG_AUTO_CANCEL = 0x00000010;

This is hexadecimal for the number 16. If you're wondering why we use these types of flags, it's because other flags will have representations:

 0x00000020
 0x00000040
 0x00000080

Each time, we go up by a power of 2. Converting this to binary, we get:

 00010000
 00100000
 01000000
 10000000

Hence, we can use a bitwise or to determine which of the flags are present, since each flag is contains only one 1 and they are all in different locations.

Steve P.
  • 14,489
  • 8
  • 42
  • 72
1

Simple explanation of what this expression you posted (probably) does:

Every integral type is represented as a list of bits. So noti.flags has a representation of something like 00101. The noti.flags variable seems to be a representation of flags i.e. options of a class. This means every bit means something else and could make the class behave in a different way, depending if the bit is 0 or 1.

The | operator is a bitwise OR operator. |= is the assignment version of the bitwise OR operator. (Behaves just like +=)

Now Notification.FLAG_AUTO_CANCEL is a constant for a single flag, possibly 10000. If you apply bitwise OR (|) to Notification.FLAG_AUTO_CANCEL and to noti.flags (00101 | 10000), the result will be 10101. This result is now assigned to noti.flags.

The expression you posted basically just sets a new flag, called FLAG_AUTO_CANCEL to the flag variable noti.flags.

Timo Türschmann
  • 4,388
  • 1
  • 22
  • 30