Changed license to CC0
[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     public void finishByte() throws IOException {
27         if (currentBytePointer != 0) {
28             outputStream.write(currentByte);
29             currentBytePointer = 0;
30         }
31     }
32
33     public void storeBits(final int data, final int bitCount)
34             throws IOException {
35         for (int i = bitCount - 1; i >= 0; i--) {
36
37             int mask = 1;
38             mask = mask << i;
39
40             final int currentBit = data & mask;
41             currentByte = currentByte << 1;
42
43             if (currentBit != 0)
44                 currentByte = currentByte | 1;
45             currentBytePointer++;
46
47             if (currentBytePointer == 8) {
48                 currentBytePointer = 0;
49                 outputStream.write(currentByte);
50                 currentByte = 0;
51             }
52         }
53     }
54
55 }