Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Create BitInputStream and BitOutputStream Classes : Page 2

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.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

BitOutputStream: Writing Bits
Consider the BitOutputStream. Each BitOutputStream instance has an OutputStream to which it writes bytes. That is, the user code writes bits to the BitOutputStream, and the BitOutputStream writes bytes to its OutputStream. Each BitOutputStream also has a buffer, which is a single byte:

Figure 1. The BitOutputStream: Each BitOutputStream has a stream to which it writes bytes, and a buffer, which is a single byte. The buffer accumulates bits until there are eight of them, at which point they can be written to the OutputStream.
Assume three bits have already been written, using the writeBit() method. These three bits exist in the buffer. Note that the class keeps track of the position where the next bit should be stored; and advances this "cursor" after writing each bit:
Figure 2. Some Bytes Are Written: Bits are stored in the buffer. The class keeps track of where to store the next bit with a "cursor" advanced after each write.
After eight bits have been written, the buffer is full—no more bits can be stored in it:

Figure 3. The Buffer Is Full: After eight bits have been written, the buffer is full.
At this point, the BitOutputStream writes the full byte to the OutputStream.
Figure 4. The Buffer Is Written to the OutputStream: The full buffer is written out to the OutputStream.
The buffer is cleared, and the cursor reset:

Figure 5. The Buffer Cleared and Cursor Reset: The full buffer is written out to the OutputStream. The buffer is cleared, and the cursor reset.
The user code continues to write bits to the BitOutputStream. After another eight bits have been written, the class writes the filled buffer byte to the OutputStream:
Figure 6. Another Byte Is Written: After another eight bits have been written, a second byte is written to the OutputStream.
This process continues until the stream is closed. If the buffer is partially full when the stream is closed, it is written out as if it had contained eight bits. The remaining empty slots take on the default value of zero.

Comment and Contribute






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



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