| 20 | import java.io.InputStream; |
| 21 | |
| 22 | public class BitInputStream extends InputStream implements BinaryConstants |
| 23 | { |
| 24 | // TODO should be byte order conscious, ie TIFF for reading |
| 25 | // samples size<8 - shuoldn't that effect their order within byte? |
| 26 | private final InputStream is; |
| 27 | |
| 28 | public BitInputStream(InputStream is) |
| 29 | { |
| 30 | this.is = is; |
| 31 | // super(is); |
| 32 | } |
| 33 | |
| 34 | public int read() throws IOException |
| 35 | { |
| 36 | if (cacheBitsRemaining > 0) |
| 37 | throw new IOException("BitInputStream: incomplete bit read"); |
| 38 | return is.read(); |
| 39 | } |
| 40 | |
| 41 | private int cache; |
| 42 | private int cacheBitsRemaining = 0; |
| 43 | private long bytes_read = 0; |
| 44 | |
| 45 | public final int readBits(int count) throws IOException |
| 46 | { |
| 47 | if (count < 8) |
| 48 | { |
| 49 | if (cacheBitsRemaining == 0) |
| 50 | { |
| 51 | // fill cache |
| 52 | cache = is.read(); |
| 53 | cacheBitsRemaining = 8; |
| 54 | bytes_read++; |
| 55 | } |
| 56 | if (count > cacheBitsRemaining) |
| 57 | throw new IOException( |
| 58 | "BitInputStream: can't read bit fields across bytes"); |
| 59 | |
| 60 | // int bits_to_shift = cache_bits_remaining - count; |
| 61 | cacheBitsRemaining -= count; |
| 62 | int bits = cache >> cacheBitsRemaining; |
| 63 | |
| 64 | switch (count) |
| 65 | { |
| 66 | case 1 : |
| 67 | return bits & 1; |
| 68 | case 2 : |
| 69 | return bits & 3; |
| 70 | case 3 : |
| 71 | return bits & 7; |
| 72 | case 4 : |
| 73 | return bits & 15; |
| 74 | case 5 : |
| 75 | return bits & 31; |
| 76 | case 6 : |
| 77 | return bits & 63; |
| 78 | case 7 : |
| 79 | return bits & 127; |
nothing calls this directly
no outgoing calls
no test coverage detected