/** * Returns a byte array containing the sequence of bits written. * * @return The byte array containing the written bits. */ public byte[] toByteArray() { // write any bits left in the buffer to the stream writeCurrentByte(); // retrieve the byte array from the stream byte[] byteArray = byteStream.toByteArray(); // reset stream for the sake of consistency byteStream.reset(); // return the byte array return byteArray; }
/** * Writes a sequence of bits to the stream. * * @param data * A Long containing the bits to write. * * @param numBits * The number of bits to write. */ public void writeLong(final long data, final int numBits) { if (numBits < 32 && data >= (1 << numBits)) { throw new IllegalArgumentException(String.format("Truncating value %d to %d-bit integer", data, numBits)); } for (int i = numBits - 1; i >= 0; i--) { // test bit boolean bit = (data >> i & 1) != 0; if (bit) { // set bit in current byte currentByte |= (1 << currentBitIndex); } // decrease current bit index --currentBitIndex; // check if current byte can be written if (currentBitIndex < 0) { writeCurrentByte(); } } }
/** * Writes a sequence of bits to the stream. * * @param data * An integer containing the bits to write. * * @param numBits * The number of bits to write. */ public void write(final int data, final int numBits) { if (numBits < 32 && data >= (1 << numBits)) { throw new IllegalArgumentException(String.format("Truncating value %d to %d-bit integer", data, numBits)); } for (int i = numBits - 1; i >= 0; i--) { // test bit boolean bit = (data >> i & 1) != 0; if (bit) { // set bit in current byte currentByte |= (1 << currentBitIndex); } // decrease current bit index --currentBitIndex; // check if current byte can be written if (currentBitIndex < 0) { writeCurrentByte(); } } }