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;
26 public void finishByte() throws IOException {
27 if (currentBytePointer != 0) {
28 outputStream.write(currentByte);
29 currentBytePointer = 0;
33 public void storeBits(final int data, final int bitCount)
35 for (int i = bitCount - 1; i >= 0; i--) {
40 final int currentBit = data & mask;
41 currentByte = currentByte << 1;
44 currentByte = currentByte | 1;
47 if (currentBytePointer == 8) {
48 currentBytePointer = 0;
49 outputStream.write(currentByte);