1 32 33 package com.imagero.uio.io; 34 35 import java.io.FilterOutputStream ; 36 import java.io.IOException ; 37 import java.io.OutputStream ; 38 39 43 public class BitOutputStream extends FilterOutputStream { 44 45 static final int[] mask = {0, 1, 3, 7, 15, 31, 63, 127, 255}; 46 47 int bitbuf; 48 protected int vbits; 49 50 private int bitsToWrite = 8; 51 52 53 public BitOutputStream(OutputStream out) { 54 super(out); 55 } 56 57 public int getBitsToWrite() { 58 return bitsToWrite; 59 } 60 61 65 public void setBitsToWrite(int bitsToWrite) { 66 this.bitsToWrite = bitsToWrite; 67 } 68 69 76 public void write(int b) throws IOException { 77 write(b, bitsToWrite); 78 } 79 80 86 public void write(int b, int nbits) throws IOException { 87 if (nbits == 0) { 88 return; 89 } 90 final int k = b & mask[nbits]; 91 bitbuf = (bitbuf << nbits) | k; 92 vbits += nbits; 93 while (vbits > 8) { 94 int c = bitbuf << (32 - vbits) >>> 24; 95 vbits -= 8; 96 out.write(c); 97 } 98 } 99 100 104 public void flush() throws IOException { 105 while (vbits > 0) { 106 int c = bitbuf << (32 - vbits) >>> 24; 107 vbits -= 8; 108 out.write(c); 109 } 110 vbits = 0; 111 bitbuf = 0; 112 out.flush(); 113 } 114 115 121 public void write(byte b[]) throws IOException { 122 write(b, 0, b.length); 123 } 124 125 133 public void write(byte b[], int off, int len) throws IOException { 134 for (int i = 0; i < len; i++) { 135 write(b[off + i]); 136 } 137 } 138 } 139 | Popular Tags |