Created
March 15, 2016 16:26
-
-
Save wtfaremyinitials/82e6a9840a7c9a5aba16 to your computer and use it in GitHub Desktop.
Easily write one bit at a time in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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