BitwiseOutputStreampublic class BitwiseOutputStream extends Object An object that provides bitwise incremental write access to a byte array.
This is useful, for example, when writing a series of fields that
may not be aligned on byte boundaries.
NOTE -- This class is not threadsafe. |
Fields Summary |
---|
private byte[] | mBuf | private int | mPos | private int | mEnd |
Constructors Summary |
---|
public BitwiseOutputStream(int startingLength)Create object from hint at desired size.
mBuf = new byte[startingLength];
mEnd = startingLength << 3;
mPos = 0;
|
Methods Summary |
---|
private void | possExpand(int bits)Allocate a new internal buffer, if needed.
if ((mPos + bits) < mEnd) return;
byte[] newBuf = new byte[(mPos + bits) >>> 2];
System.arraycopy(mBuf, 0, newBuf, 0, mEnd >>> 3);
mBuf = newBuf;
mEnd = newBuf.length << 3;
| public void | skip(int bits)Increment the current position, implicitly writing zeros.
possExpand(bits);
mPos += bits;
| public byte[] | toByteArray()Return byte array containing accumulated data, sized to just fit.
int len = (mPos >>> 3) + ((mPos & 0x07) > 0 ? 1 : 0); // &7==%8
byte[] newBuf = new byte[len];
System.arraycopy(mBuf, 0, newBuf, 0, len);
return newBuf;
| public void | write(int bits, int data)Write some data and increment the current position.
The 8-bit limit on access to bitwise streams is intentional to
avoid endianness issues.
if ((bits < 0) || (bits > 8)) {
throw new AccessException("illegal write (" + bits + " bits)");
}
possExpand(bits);
data &= (-1 >>> (32 - bits));
int index = mPos >>> 3;
int offset = 16 - (mPos & 0x07) - bits; // &7==%8
data <<= offset;
mPos += bits;
mBuf[index] |= data >>> 8;
if (offset < 8) mBuf[index + 1] |= data & 0xFF;
| public void | writeByteArray(int bits, byte[] arr)Write data in bulk from a byte array and increment the current position.
for (int i = 0; i < arr.length; i++) {
int increment = Math.min(8, bits - (i << 3));
if (increment > 0) {
write(increment, (byte)(arr[i] >>> (8 - increment)));
}
}
|
|