|
|
The following table shows the standard bitwise operators in Java and a description of them.
Operator | Description |
---|---|
& | Bitwise AND |
| | Bitwise inclusive-OR (generally known as OR) |
^ | Bitwise exclusive-OR (generally known as XOR) |
~ | Bitwise NOT |
To illustrate the function of these bitwise operators, we can use two byte values, A and B, which in java could be represented by a variable of type byte. The following table shows the binary notation of A and B (as there are 8 bits in a byte).
Byte | Binary Value |
---|---|
A | 01101010 |
B | 11110000 |
The AND (&) operator tests two bits and returns the resulting bit true if both test bits are true; otherwise, the return bit is false. The following table shows the result of A AND B.
Byte | Bits | |||||||
---|---|---|---|---|---|---|---|---|
A | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 |
B | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 |
A AND B | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 |
The OR (|) operator tests two bits and returns the resulting bit true if any or both of the test bits are true; if they are both false, the return bit is also false. The following table shows the result of A OR B.
Byte | Bits | |||||||
---|---|---|---|---|---|---|---|---|
A | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 |
B | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 |
A AND B | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 |
The XOR (^) operator tests two bits and returns the resulting bit true if one, and only one, of the bits is true; otherwise, if the two values are equal, the return bit is false. The following table shows the result of A XOR B.
Byte | Bits | |||||||
---|---|---|---|---|---|---|---|---|
A | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 |
B | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 |
A AND B | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 0 |
The NOT (~) operator will invert all of the bits, where ones becomes zeros and zeros become ones, and is therefore a unary operator used with only one operand, whereas the other bitwise operators we have just seen were tested against two operands (binary operators), A and B. The following table shows the result of a NOT operation on byte A.
Byte | Bits | |||||||
---|---|---|---|---|---|---|---|---|
A | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 |
NOT A | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 |
The bitwise AND, OR, and XOR operators can also be used with boolean expressions, as Boolean values effectively only contain one bit that is either true or false. This can be implemented in Java as follows:
boolean musicOn = true; boolean televisionOn = true; boolean areBothOn = musicOn & televisionOn; // true boolean areAnyOn = musicOn | televisionOn; // true boolean isOnlyOneOn = musicOn ^ televisionOn; // false
There are also assignment operators for these three bitwise operators, as shown in the following table.
Operator | Description |
---|---|
&= | Bitwise AND assignment |
|= | Bitwise inclusive-OR assignment |
^= | Bitwise exclusive-XOR assignment |
These assignment operators can be used in the same way that we used the previous set of assignment operators.
|
|