= bitwise OR and assign example
This question already has an answer here:
a |= b;
is the same as
a = (a | b);
It calculates the bitwise OR of the two operands, and assigns the result to the left operand.
To explain your example code:
for (String search : textSearch.getValue())
matches |= field.contains(search);
I presume matches
is a boolean
; this means that the bitwise operators behave the same as logical operators.
On each iteration of the loop, it OR
s the current value of matches
with whatever is returned from field.contains()
. This has the effect of setting it to true
if it was already true, or if field.contains()
returns true.
So, it calculates if any of the calls to field.contains()
, throughout the entire loop, has returned true
.
a |= b
is the same as a = (a | b)
Boolean Variables
In a boolean
context, it means:
if (b) {
a = true;
}
that is, if b
is true then a
will be true, otherwise a
will be unmodified.
Bitwise Operations
In a bit wise context it means that every binary bit that's set in b
will become set in a
. Bits that are clear in b
will be unmodified in a
.
So if bit 0 is set in b
, it'll also become set in a
, per the example below:
This will set the bottom bit of an integer:
a |= 0x01
This will clear the bottom bit:
a &= ~0x01
This will toggle the bottom bit:
a ^= 0x01;
This code:
int i = 5;
i |= 10;
is equivalent to this code:
int i = 5;
i = i | 10;
Similarly, this code:
boolean b = false;
b |= true;
is equivalent to this one:
boolean b = false;
b = b | true;
In the first example, a bit-wise OR is being performed. In the second example, a boolean OR is performed.
链接地址: http://www.djcxy.com/p/36374.html上一篇: C#按位运算符
下一篇: =按位OR并分配示例