The Java language provides 4 operators that perform bitwise or logical operations on integer or boolean operands.
~
) operator is a unary operator that performs a bitwise or logical inversion of the bits of one operand; see JLS 15.15.5..&
) operator is a binary operator that performs a bitwise or logical "and" of two operands; see JLS 15.22.2..|
) operator is a binary operator that performs a bitwise or logical "inclusive or" of two operands; see JLS 15.22.2..^
) operator is a binary operator that performs a bitwise or logical "exclusive or" of two operands; see JLS 15.22.2..The logical operations performed by these operators when the operands are booleans can be summarized as follows:
A | B | ~A | A & B | A | B | A ^ B |
---|---|---|---|---|---|
0 | 0 | 1 | 0 | 0 | 0 |
0 | 1 | 1 | 0 | 1 | 1 |
1 | 0 | 0 | 0 | 1 | 1 |
1 | 1 | 0 | 1 | 1 | 0 |
Note that for integer operands, the above table describes what happens for individual bits. The operators actually operate on all 32 or 64 bits of the operand or operands in parallel.
The usual arithmetic conversions apply when the operands are integers. Common use-cases for the bitwise operators
The ~
operator is used to reverse a boolean value, or change all the bits in an integer operand.
The &
operator is used for "masking out" some of the bits in an integer operand. For example:
int word = 0b00101010;
int mask = 0b00000011; // Mask for masking out all but the bottom
// two bits of a word
int lowBits = word & mask; // -> 0b00000010
int highBits = word & ~mask; // -> 0b00101000
The |
operator is used to combine the truth values of two operands. For example:
int word2 = 0b01011111;
// Combine the bottom 2 bits of word1 with the top 30 bits of word2
int combined = (word & mask) | (word2 & ~mask); // -> 0b01011110
The ^
operator is used for toggling or "flipping" bits:
int word3 = 0b00101010;
int word4 = word3 ^ mask; // -> 0b00101001
For more examples of the use of the bitwise operators, see Bit Manipulation