2 * Svjatoslav Commons - shared library of common functionality.
3 * Copyright ©2012-2019, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of version 3 of the GNU Lesser General Public License
7 * or later as published by the Free Software Foundation.
10 package eu.svjatoslav.commons.data;
13 import java.io.IOException;
14 import java.io.OutputStream;
17 * Write individual bits to the output stream.
19 public class BitOutputStream {
21 private final OutputStream outputStream;
22 private int currentByte;
23 private int currentBytePointer;
25 public BitOutputStream(final OutputStream outputStream) {
27 currentBytePointer = 0;
28 this.outputStream = outputStream;
31 public void finishByte() throws IOException {
32 if (currentBytePointer != 0) {
33 outputStream.write(currentByte);
34 currentBytePointer = 0;
38 public void storeBits(final int data, final int bitCount)
40 for (int i = bitCount - 1; i >= 0; i--) {
45 final int currentBit = data & mask;
46 currentByte = currentByte << 1;
49 currentByte = currentByte | 1;
52 if (currentBytePointer == 8) {
53 currentBytePointer = 0;
54 outputStream.write(currentByte);