What does the |= operator do in Java?

前端 未结 6 688
暗喜
暗喜 2020-12-06 10:15

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

Adding vibration

You can alert the user with th

相关标签:
6条回答
  • 2020-12-06 10:39

    |= 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
    
    0 讨论(0)
  • 2020-12-06 10:43

    bitwise OR operator

    0 讨论(0)
  • 2020-12-06 10:45

    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
    
    0 讨论(0)
  • 2020-12-06 10:46

    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
    
    0 讨论(0)
  • 2020-12-06 10:50

    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.

    0 讨论(0)
  • 2020-12-06 10:55

    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.

    0 讨论(0)
提交回复
热议问题