Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Create BitInputStream and BitOutputStream Classes : Page 3

Although the JDK 1.4 has many Stream classes, it doesn't contain classes for reading and writing single bits. Extend your tool set by creating these BitInputStream and BitOutputStream classes.


advertisement
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 is the 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 the cursor.

 
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 buffer.


 
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.


Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date