开发者

What does the |= operator do in Java?

While reading the Android guide to Notifications, I stumbled across this:

Adding vibration

You can alert the user with the the default vibration pattern or with a vibration pattern defined by your application.

To use the default pattern, add "DEFAULT_VIBRATE" to 开发者_StackOverflowthe defaults field:

notification.defaults |= Notification.DEFAULT_VIBRATE;

What this does is clear: it adds the DEFAULT_VIBRATE flag to the default flags of the notification object. But what does the |= operator do in Java? It looks like an "OR", but how does it work?

Can you provide an example using numbers?

Thanks


|= is a bitwise-OR-assignment operator. It takes the current value of the LHS, bitwise-ors the RHS, and assigns the value back to the LHS (in a similar fashion to += does with addition).

For example:

foo = 32;   // 32 =      0b00100000
bar = 9;    //  9 =      0b00001001
baz = 10;   // 10 =      0b00001010
foo |= bar; // 32 | 9  = 0b00101001 = 41
            // now foo = 41
foo |= baz; // 41 | 10 = 0b00101011 = 43
            // now foo = 43


a |= x is a = a | x, and | is "bitwise inclusive OR"

Whenever such questions arise, check the official tutorial on operators.

Each operator has an assignment form:

+= -= *= /= %= &= ^= |= <<= >>= >>>=

Where a OP= x is translated to a = a OP x

And about bitwise operations:

   0101 (decimal 5)
OR 0011 (decimal 3)
 = 0111 (decimal 7)

The bitwise OR may be used in situations where a set of bits are used as flags; the bits in a single binary numeral may each represent a distinct Boolean variable. Applying the bitwise OR operation to the numeral along with a bit pattern containing 1 in some positions will result in a new numeral with those bits set.


It is a short hand notation for performing a bitwise OR and an assignment in one step.

x |= y is equivalent to x = x | y

This can be done with many operators, for example:

x += y
x -= y
x /= y
x *= y
etc.

An example of the bitwise OR using numbers.. if either bit is set in the operands the bit will be set in the result. So, if:

x = 0001 and
y = 1100 then
--------
r = 1101


In this case, notification.defaults is a bit array. By using |=, you're adding Notification.DEFAULT_VIBRATE to the set of default options. Inside Notification, it is likely that the presence of this particular value will be checked for like so:

notification.defaults & Notification.DEFAULT_VIBRATE != 0 // Present


This is the bit wise OR operator. If notifications.default is 0b00000001 in binary form and Notification.DEFAULT_VIBRATE is 0b11000000, then the result will be 0b11000001.


bitwise OR operator

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜