public class BinaryOutput { private static BufferedOutputStream out; private static int n; private static int buffer; public BinaryOutput(File f) throws FileNotFoundException { out = new BufferedOutputStream(new FileOutputStream(f)); } public static void writeBit(boolean bit) throws IOException { buffer = buffer << 1; if (bit == true) { buffer = buffer | 1; } n++; if (n == 8) { out.write(buffer); buffer=0; n=0; } } /** * Writes out char as a byte * * @param character * @throws IOException */ public static void writeByteChar(char character) throws IOException { int b = (int) character; writeByte(b); } /** * If buffer is empty writes out a single byte, else converts into bits * * @param b * @throws IOException */ private static void writeByte(int b) throws IOException { if (n == 0) { out.write(b); } else { for (int i = 0; i < 8; i++) { boolean bit = ((b >>> (8 - i - 1)) & 1) == 1; writeBit(bit); } } } }
Buffer resetuje się za każdym razem gdy n=8 i zostaje zapisany w pliku jako jeden bajt (8-bitów). Co w wypadku gdy przed zamknięciem BufferedOutputStream n nie osiągnie wartości 8 a nadal będę chciała wypisać buffer jako 1 bajt? Czy można w jakiś sposób wypisać bajt np. 3 bitowy?