Java Reference
In-Depth Information
The result of the expression is now zero because the third bit of
indicators
is zero.
To set a particular bit on, you can use the
|
operator, so to set the third bit in
indicators
on, you
can write:
indicators = indicators | 0x4; // Set the 3rd bit on
We can see how this applies to the last value we had for indicators:
Hexadecimal
Binary
indicators
0xFF09
1111
1111
0000
1001
mask value
0x4
0000
0000
0000
0100
indicators | 0x4
0xFF0D
1111
1111
0000
1101
As you can see, the effect is just to switch the third bit of indicators on. All the others are unchanged. Of
course, if the bit were already on, it would stay on.
The bitwise operators can also be used in the
op=
form. Setting the third bit in the variable
indicators
is usually written as:
indicators |= 0x4;
Although there is nothing wrong with the original statement we wrote, the one above 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 &= ~0x4; // Set the 3rd bit off
With
indicators
having the value
0xFF07
, this would work as follows:
Hexadecimal
Binary
indicators
0xFF07
1111
1111
0000
0111
mask value
0x4
0000
0000
0000
0100
~0x4
0xFFFB
1111
1111
1111
1011
indicators & ~0x4
0xFF03
1111
1111
0000
0011
The
^
operator has the slightly surprising ability to interchange two values without moving either value
somewhere else. The need for this turns up most frequently in tricky examination questions. If you
execute the three statements: