Java Reference
In-Depth Information
Q
:
Since binary is based on powers of two, can the shift operators be used as a
shortcut for multiplying or dividing an integer by two?
A
:
Yes. The bitwise shift operators can be used to perform very fast multiplication or di-
vision by two. A shift left doubles a value. A shift right halves it.
Try This 5-3
A ShowBits Class
This project creates a class called
ShowBits
that enables you to display in binary the bit
pattern for any integer value. Such a class can be quite useful in programming. For ex-
ample, if you are debugging device-driver code, then being able to monitor the data stream
in binary is often a benefit.
1.
Create a file called
ShowBitsDemo.java
.
2.
Begin the
ShowBits
class as shown here:
ShowBits
creates objects that display a specified number of bits. For example, to cre-
ate an object that will display the low-order 8 bits of some value, use
The number of bits to display is stored in
numbits
.
3.
To actually display the bit pattern,
ShowBits
provides the method
show( )
, which is
shown here: