…lines 1–78 unchanged (78 lines)
79 * @throws IOException on error
80 */
81 public long readBits(final int count) throws IOException {
82 if (count < 0 || count > MAXIMUM_CACHE_SIZE) {
83 throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE);
84 }
85 while (bitsCachedSize < count && bitsCachedSize < 57) {
86 final long nextByte = in.read();
87 if (nextByte < 0) {
88 return nextByte;
89 }
90 if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
91 bitsCached |= (nextByte << bitsCachedSize);
92 } else {
93 bitsCached <<= 8;
94 bitsCached |= nextByte;
95 }
96 bitsCachedSize += 8;
97 }
98 int overflowBits = 0;
99 long overflow = 0l;
100 if (bitsCachedSize < count) {
101 // bitsCachedSize >= 57 and left-shifting it 8 bits would cause an overflow
102 int bitsToAddCount = count - bitsCachedSize;
103 overflowBits = 8 - bitsToAddCount;
104 final long nextByte = in.read();
105 if (nextByte < 0) {
106 return nextByte;
107 }
108 if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
109 long bitsToAdd = nextByte & MASKS[bitsToAddCount];
110 bitsCached |= (bitsToAdd << bitsCachedSize);
111 overflow = (nextByte >>> bitsToAddCount) & MASKS[overflowBits];
112 } else {
113 bitsCached <<= bitsToAddCount;
114 long bitsToAdd = (nextByte >>> (overflowBits)) & MASKS[bitsToAddCount];
115 bitsCached |= bitsToAdd;
116 overflow = nextByte & MASKS[overflowBits];
117 }
118 bitsCachedSize = count;
119 }
120
121 final long bitsOut;
122 if (overflowBits == 0) {
123 if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
124 bitsOut = (bitsCached & MASKS[count]);
125 bitsCached >>>= count;
126 } else {
127 bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count];
128 }
129 bitsCachedSize -= count;
130 } else {
131 bitsOut = bitsCached & MASKS[count];
132 bitsCached = overflow;
133 bitsCachedSize = overflowBits;
134 }
135 return bitsOut;
136 }
137}
138