2 * Svjatoslav Commons - shared library of common functionality. Author: Svjatoslav Agejenko.
3 * This project is released under Creative Commons Zero (CC0) license.
5 package eu.svjatoslav.commons.data;
8 import java.io.IOException;
9 import java.io.OutputStream;
12 * Write individual bits to the output stream.
14 public class BitOutputStream {
16 private final OutputStream outputStream;
17 private int currentByte;
18 private int currentBytePointer;
20 public BitOutputStream(final OutputStream outputStream) {
22 currentBytePointer = 0;
23 this.outputStream = outputStream;
27 * Finish writing the last byte.
28 * @throws IOException If an I/O error occurs.
30 public void finishByte() throws IOException {
31 if (currentBytePointer != 0) {
32 outputStream.write(currentByte);
33 currentBytePointer = 0;
38 * Write bits to the output stream.
39 * @param data Data to write.
40 * @param bitCount Number of bits to write.
41 * @throws IOException If an I/O error occurs.
43 public void storeBits(final int data, final int bitCount)
45 for (int i = bitCount - 1; i >= 0; i--) {
50 final int currentBit = data & mask;
51 currentByte = currentByte << 1;
54 currentByte = currentByte | 1;
57 if (currentBytePointer == 8) {
58 currentBytePointer = 0;
59 outputStream.write(currentByte);