/** * Gets the specified amount of bits from the buffer. * * @param amount The amount of bits. * @return The value. * @throws IllegalStateException If the reader is not in bit access mode. * @throws IllegalArgumentException If the number of bits is not between 1 and 31 inclusive. */ public int getBits(int amount) { Preconditions.checkArgument(amount >= 0 && amount <= 32, "Number of bits must be between 1 and 32 inclusive."); checkBitAccess(); int bytePos = bitIndex >> 3; int bitOffset = 8 - (bitIndex & 7); int value = 0; bitIndex += amount; for (; amount > bitOffset; bitOffset = 8) { value += (buffer.getByte(bytePos++) & DataConstants.BIT_MASK[bitOffset]) << amount - bitOffset; amount -= bitOffset; } if (amount == bitOffset) { value += buffer.getByte(bytePos) & DataConstants.BIT_MASK[bitOffset]; } else { value += buffer.getByte(bytePos) >> bitOffset - amount & DataConstants.BIT_MASK[amount]; } return value; }