Skip to content
Snippets Groups Projects
Commit 8aeb9e04 authored by Vojtech Moravec's avatar Vojtech Moravec
Browse files

OutBitStream prototype.

parent b2c7bb0f
Branches
No related tags found
No related merge requests found
import cli.CliConstants;
import cli.ParsedCliOptions;
import compression.io.OutMemoryBitStream;
import compression.io.OutBitStream;
import org.apache.commons.cli.*;
import org.jetbrains.annotations.NotNull;
......@@ -11,7 +11,7 @@ public class DataCompressor {
public static void main(String[] args) throws IOException {
OutMemoryBitStream bitStream = new OutMemoryBitStream(null, 3, 64);
OutBitStream bitStream = new OutBitStream(null, 3, 64);
bitStream.write(0);
bitStream.write(1);
bitStream.write(2);
......
package compression.io;
import java.io.IOException;
import java.io.OutputStream;
public class OutBitStream {
private OutputStream outStream;
private byte[] buffer;
private int bufferPosition;
private byte bitBuffer = 0x00;
private byte bitBufferSize = 0x00;
private final int bitsPerValue;
public OutBitStream(OutputStream outputStream, final int bitsPerValue, final int bufferSize) {
this.bitsPerValue = bitsPerValue;
buffer = new byte[bufferSize];
bufferPosition = 0;
bitBuffer = 0;
bitBufferSize = 0;
outStream = outputStream;
}
/**
* Flush the memory buffer to the underlying stream.
*/
private void flushBuffer() throws IOException {
outStream.write(buffer, 0, bufferPosition);
bufferPosition = 0;
}
/**
* Flush the bit buffer into the memory buffer.
*/
private void flushBitBuffer() throws IOException {
if (bitBufferSize > 0) {
buffer[bufferPosition++] = bitBuffer;
bitBuffer = 0;
bitBufferSize = 0;
if (bufferPosition == buffer.length) {
flushBuffer();
}
}
}
public void forceFlush() throws IOException {
flushBitBuffer();
flushBuffer();
}
/**
* Write bit to the memory bit buffer.
*
* @param bit True for 1
*/
private void writeBit(final int bit) throws IOException {
// ++bitBufferSize;
if (bit > 0) {
// bitBuffer |= (1 << (8 - bitBufferSize));
bitBuffer |= (1 << bitBufferSize);
}
++bitBufferSize;
if (bitBufferSize == 8) {
flushBitBuffer();
}
}
// public void write(final byte value) {
//
// }
//
// public void write(final short value) {
//
// }
public void write(final int value) throws IOException {
int bit;
for (int shift = 0; shift < bitsPerValue; shift++) {
bit = (value & (1 << shift));
//bit = (value & (1 << (31 - shift)));
writeBit(bit);
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment