FileDocCategorySizeDatePackage
BitwiseOutputStream.javaAPI DocAndroid 5.1 API4099Thu Mar 12 22:22:10 GMT 2015com.android.internal.util

BitwiseOutputStream

public 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.

param
startingLength initial internal byte array length in bytes

        mBuf = new byte[startingLength];
        mEnd = startingLength << 3;
        mPos = 0;
    
Methods Summary
private voidpossExpand(int bits)
Allocate a new internal buffer, if needed.

param
bits additional bits to be accommodated

        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 voidskip(int bits)
Increment the current position, implicitly writing zeros.

param
bits the amount by which to increment the position

        possExpand(bits);
        mPos += bits;
    
public byte[]toByteArray()
Return byte array containing accumulated data, sized to just fit.

return
newly allocated byte array

        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 voidwrite(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.

param
bits the amount of data to write (gte 0, lte 8)
param
data to write, will be masked to expose only bits param from lsb

        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 voidwriteByteArray(int bits, byte[] arr)
Write data in bulk from a byte array and increment the current position.

param
bits the amount of data to write
param
arr the byte array containing data to be written

        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)));
            }
        }