Skip to content

Instantly share code, notes, and snippets.

@wtfaremyinitials
Created March 15, 2016 16:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wtfaremyinitials/82e6a9840a7c9a5aba16 to your computer and use it in GitHub Desktop.
Save wtfaremyinitials/82e6a9840a7c9a5aba16 to your computer and use it in GitHub Desktop.
Easily write one bit at a time in Java
import java.io.*;
public class ByteOutputStream extends FileOutputStream {
byte buffer;
byte pos;
public ByteOutputStream(File file) throws FileNotFoundException {
super(file);
buffer = 0x00;
}
public void write(byte bit) throws IOException {
if(!(bit == 0 || bit == 1))
throw new RuntimeException("A bit can only be a 1 or 0");
buffer = (byte)(buffer << 1);
buffer |= bit;
pos++;
if(pos == 8)
flushByte();
}
public void write(byte[] bits) throws IOException {
for(byte bit : bits)
write(bit);
}
public void close() throws IOException {
if(pos != 0) {
buffer = (byte)(buffer << (8 - pos));
flushByte();
}
super.close();
}
private void flushByte() throws IOException {
super.write(buffer);
buffer = 0x00;
pos = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment