1 32 33 package com.imagero.uio.io; 34 35 import java.io.FilterInputStream ; 36 import java.io.IOException ; 37 import java.io.InputStream ; 38 39 43 public class BitInputStream extends FilterInputStream { 44 45 int vbits = 0; 46 int bitbuf = 0; 47 48 private int bitsToRead = 8; 49 50 public BitInputStream(InputStream in) { 51 super(in); 52 } 53 54 58 public int getBitsToRead() { 59 return bitsToRead; 60 } 61 62 66 public void setBitsToRead(int bitsToRead) { 67 if(bitsToRead > 8) { 68 throw new IllegalArgumentException (); 69 } 70 this.bitsToRead = bitsToRead; 71 } 72 73 public int read() throws IOException { 74 return read(bitsToRead); 75 } 76 77 public int read(int nbits) throws IOException { 78 int ret; 79 if (nbits == 0) { 81 return 0; 82 } 83 if (nbits > 8) { 85 throw new IllegalArgumentException ("max 8 bits can be read at once"); 86 } 87 if (nbits > vbits) { 89 fillBuffer(nbits); 90 } 91 if (vbits == 0) { 93 return -1; 94 } 95 ret = bitbuf << (32 - vbits) >>> (32 - nbits); 100 vbits -= nbits; 101 102 if(vbits < 0) { 103 vbits = 0; 104 } 105 106 return ret; 107 } 108 109 public int read(byte b[]) throws IOException { 110 return read(b, 0, b.length); 111 } 112 113 123 public int read(byte b[], int off, int len) throws IOException { 124 if (len <= 0) { 125 return 0; 126 } 127 int c = read(); 128 if (c == -1) { 129 return -1; 130 } 131 b[off] = (byte) c; 132 133 int i = 1; 134 for (; i < len; ++i) { 135 c = read(); 136 if (c == -1) { 137 break; 138 } 139 b[off + i] = (byte) c; 140 } 141 return i; 142 } 143 144 147 public void resetBuffer() { 148 vbits = 0; 149 bitbuf = 0; 150 } 151 152 160 public long skip(long n) throws IOException { 161 if (vbits == 0) { 162 return in.skip(n); 163 } 164 else { 165 int b = (vbits + 8) / 8; 166 in.skip(n - b); 167 int vbits = this.vbits; 168 resetBuffer(); 169 fillBuffer(vbits); 170 return n; 171 } 172 } 173 174 private void fillBuffer(int nbits) throws IOException { 175 int c; 176 while (vbits < nbits) { 177 c = in.read(); 178 if (c == -1) { 179 break; 180 } 181 bitbuf = (bitbuf << 8) + (c & 0xFF); 182 vbits += 8; 183 } 184 } 185 186 public int getBitOffset() { 187 return 7 - (vbits % 8); 188 } 189 } 190 | Popular Tags |