The Bitwise and Logical Operators

suggest change

The Java language provides 4 operators that perform bitwise or logical operations on integer or boolean operands.

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.

Operand types and result types.

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 http://stackoverflow.com/documentation/java/1177/bit-manipulation#t=201610101439344327372

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents