Java Reference
In-Depth Information
The AND operator is also useful when you want to determine whether a bit is on or off.
For example, this statement determines whether bit 4 in
status
is set:
The number 8 is used because it translates into a binary value that has only the 4th bit set.
Therefore, the
if
statement can succeed only when bit 4 of
status
is also on. An interesting
use of this concept is to show the bits of a
byte
value in binary format.
The output is shown here:
The
for
loop successively tests each bit in
val
, using the bitwise AND, to determine wheth-
er it is on or off. If the bit is on, the digit
1
is displayed; otherwise,
0
is displayed. In
Try
display the bits in any type of integer.
The bitwise OR, as the reverse of AND, can be used to turn bits on. Any bit that is set to
1 in either operand will cause the corresponding bit in the result to be set to 1. For example: