BitInputStream: Reading Bits
The process of reading from a BitInputStream is similar. Just as a BitOutputStream
has an OutputStream
, a BitInputStream
has an InputStream
. And it
also has a byte buffer:
|Figure 7. BitInputStream Transfers: The BitInputStream transfers one byte at a time from the InputStream to the buffer.|
Note that the InputStream is shown already filled with data. This is because this InputStream
source of the bits for the BitInputStream
. The amount of data depends on the contents of the InputStream
The first time that user code calls the readBit() method, there are no bits in the buffer. The
BitInputStream must first read a single byte from the InputStream and store it in the buffer.
|Figure 8. Filling the Buffer: Before reading bits, the
class must fill the buffer with data from the InputStream.|
Now that the buffer contains some bits, you can return the first one to the calling code. You must also remember to advance
|Figure 9. Returning a Bit: Now that the buffer contains
some bits, it can return one to the calling code.|
Each time the user calls readBit()
, the BitInputStream returns another bit from the buffer.
|Figure 10. More Calls to readBit(): Each time the
user calls readBit(), the BitInputStream returns another bit from the buffer.|
After reading the eighth bit, there are no more bits available in the buffer. The cursor has moved "off the end" of the
|Figure 11. The Buffer Is Drained: There are no more bits
available in the buffer.|
The next time the code calls readBit()
is called, you must get another byte from the InputStream
and place that in the buffer.
|Figure 12. Refilling the Buffer: The BitInputStream gets
another byte from the InputStream and places it in the buffer.|
After refilling the buffer, you can return the next bit and advance the cursor.
|Figure 13. Returning Another Bit: Return the first bit
from the newly-filled buffer.|