Updated latest released version number in documentation.
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / data / BitOutputStream.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality. Author: Svjatoslav Agejenko.
3  * This project is released under Creative Commons Zero (CC0) license.
4  */
5 package eu.svjatoslav.commons.data;
6
7
8 import java.io.IOException;
9 import java.io.OutputStream;
10
11 /**
12  * Write individual bits to the output stream.
13  */
14 public class BitOutputStream {
15
16     private final OutputStream outputStream;
17     private int currentByte;
18     private int currentBytePointer;
19
20     public BitOutputStream(final OutputStream outputStream) {
21         currentByte = 0;
22         currentBytePointer = 0;
23         this.outputStream = outputStream;
24     }
25
26     /**
27      * Finish writing the last byte.
28      * @throws IOException If an I/O error occurs.
29      */
30     public void finishByte() throws IOException {
31         if (currentBytePointer != 0) {
32             outputStream.write(currentByte);
33             currentBytePointer = 0;
34         }
35     }
36
37     /**
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.
42      */
43     public void storeBits(final int data, final int bitCount)
44             throws IOException {
45         for (int i = bitCount - 1; i >= 0; i--) {
46
47             int mask = 1;
48             mask = mask << i;
49
50             final int currentBit = data & mask;
51             currentByte = currentByte << 1;
52
53             if (currentBit != 0)
54                 currentByte = currentByte | 1;
55             currentBytePointer++;
56
57             if (currentBytePointer == 8) {
58                 currentBytePointer = 0;
59                 outputStream.write(currentByte);
60                 currentByte = 0;
61             }
62         }
63     }
64
65 }