| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package uk.me.parabola.imgfmt.app; |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
public class BitReader { |
| 25 |
private final byte[] buf; |
| 26 |
private int bitPosition; |
| 27 |
|
| 28 |
public BitReader(byte[] buf) { |
| 29 |
this.buf = buf; |
| 30 |
} |
| 31 |
|
| 32 |
public boolean get1() { |
| 33 |
int off = bitPosition % 8; |
| 34 |
byte b = buf[bitPosition / 8]; |
| 35 |
|
| 36 |
bitPosition++; |
| 37 |
return ((b >> off) & 1) == 1; |
| 38 |
} |
| 39 |
|
| 40 |
public int get(int n) { |
| 41 |
int res = 0; |
| 42 |
|
| 43 |
int pos = 0; |
| 44 |
while (pos < n) { |
| 45 |
int index = bitPosition / 8; |
| 46 |
int off = bitPosition % 8; |
| 47 |
|
| 48 |
byte b = buf[index]; |
| 49 |
b >>= off; |
| 50 |
int nbits = n - pos; |
| 51 |
if (nbits > (8-off)) |
| 52 |
nbits = 8 - off; |
| 53 |
|
| 54 |
int mask = ((1 << nbits) - 1); |
| 55 |
res |= ((b & mask) << pos); |
| 56 |
pos += nbits; |
| 57 |
bitPosition += nbits; |
| 58 |
} |
| 59 |
|
| 60 |
return res; |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
public int sget(int n) { |
| 72 |
int res = get(n); |
| 73 |
int top = 1 << (n - 1); |
| 74 |
|
| 75 |
if ((res & top) != 0) { |
| 76 |
int mask = top - 1; |
| 77 |
res = ~mask | res; |
| 78 |
} |
| 79 |
return res; |
| 80 |
} |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
public int sget2(int n) { |
| 87 |
int top = 1 << (n - 1); |
| 88 |
int mask = top - 1; |
| 89 |
int base = 0; |
| 90 |
|
| 91 |
int res = get(n); |
| 92 |
while (res == top) { |
| 93 |
|
| 94 |
base += mask; |
| 95 |
res = get(n); |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
if ((res & top) == 0) |
| 101 |
res += base; |
| 102 |
else |
| 103 |
res = (res | ~mask) - base; |
| 104 |
|
| 105 |
return res; |
| 106 |
} |
| 107 |
|
| 108 |
public int getBitPosition() { |
| 109 |
return bitPosition; |
| 110 |
} |
| 111 |
|
| 112 |
public int getNumberOfBits() { |
| 113 |
return buf.length * 8; |
| 114 |
} |
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
public String remainder() { |
| 124 |
int save = bitPosition; |
| 125 |
StringBuilder sb = new StringBuilder(); |
| 126 |
while (bitPosition < buf.length * 8) { |
| 127 |
sb.insert(0, get1() ? "1" : "0"); |
| 128 |
} |
| 129 |
bitPosition = save; |
| 130 |
return sb.toString(); |
| 131 |
} |
| 132 |
} |