public void writeBits(int amount, int value) {
			if (getAccessType() != AccessType.BIT_ACCESS) {
				throw new IllegalStateException("Illegal access type.");
			}
			if (amount < 0 || amount > 32) {
				throw new IllegalArgumentException("Number of bits must be between 1 and 32 inclusive.");
			}

			int bytePos = getBitPosition() >> 3;
			int bitOffset = 8 - (getBitPosition() & 7);
			setBitPosition(getBitPosition() + amount);

			// Re-size the buffer if need be.
			int requiredSpace = bytePos - buffer.writerIndex() + 1;
			requiredSpace += (amount + 7) / 8;
			if (buffer.writableBytes() < requiredSpace) {
				ChannelBuffer old = buffer;
				buffer = ChannelBuffers.buffer(old.capacity() + requiredSpace);
				buffer.writeBytes(old);
			}
			for (; amount > bitOffset; bitOffset = 8) {
				byte tmp = buffer.getByte(bytePos);
				tmp &= ~BIT_MASK[bitOffset];
				tmp |= (value >> (amount - bitOffset)) & BIT_MASK[bitOffset];
				buffer.setByte(bytePos++, tmp);
				amount -= bitOffset;
			}
			if (amount == bitOffset) {
				byte tmp = buffer.getByte(bytePos);
				tmp &= ~BIT_MASK[bitOffset];
				tmp |= value & BIT_MASK[bitOffset];
				buffer.setByte(bytePos, tmp);
			} else {
				byte tmp = buffer.getByte(bytePos);
				tmp &= ~(BIT_MASK[amount] << (bitOffset - amount));
				tmp |= (value & BIT_MASK[amount]) << (bitOffset - amount);
				buffer.setByte(bytePos, tmp);
			}
		}