Java Reference
In-Depth Information
mask 0b0000_0000_0000_0100
indicators & mask0b0000_0000_0000_0000
The result of the expression is now zero because the third bit of indicators is zero.
As I said, you can use the | operator to set a particular bit on. For example, to set the third bit in indic-
ators on, you can write the following:
indicators = indicators | mask; // Set the 3rd bit on
You can see how this applies to the last value you had for indicators :
indicators 0b1111_1111_0000_1001
mask 0b0000_0000_0000_0100
indicators | mask0b1111_1111_0000_1101
As you can see, the effect is just to switch the third bit of indicators on, leaving all the other bits un-
changed. Of course, if the third bit was already on, it would stay on.
You can also use the bitwise operators in the op= form. Setting the third bit in the variable indicators
is usually written as:
indicators |= mask;
Although there is nothing wrong with the original statement, the preceding one is just a bit more concise.
To set a bit off you need to use the & operator again, with a mask that has 0 for the bit you want as 0, and
1 for all the others. To set the third bit of indicators off you could write:
indicators &= ~mask; // Set the 3rd bit off, mask value 0x4
The ~ operator provides a useful way of specifying a value with all bits 1 apart from one. The mask vari-
able contains a value with the third bit as 1 and the other bits as 0. Applying the ~ operator to this flips each
bit, so that the 0 bits are 1 and the 1 bit is zero. With indicators having the value 0xFF07 , this would work
as follows:
indicators 0b1111_1111_0000_0111
mask 0b0000_0000_0000_0100
~mask 0b1111_1111_1111_0100
indicators & ~mask0b1111_1111_0000_0011
Let's see some of these bitwise operations in action.
TRY IT OUT: Bitwise AND and OR Operations
This example exercises some of the operations that you saw in the previous section:
import static java.lang.Integer.toBinaryString;
public class BitwiseOps {
public static void main(String[] args) {
int indicators = 0b1111_1111_0000_0111; // Same as 0xFF07
int selectBit3 = 0b0000_0000_0000_0100; // Mask to select the
Search WWH ::




Custom Search