Thursday, October 21, 2010

Specific bits from byte

Bit Iteration:
Following code shows how to iterate between bits of a byte array. The original class was taken from somewhere else i have just customized it to get number of desired bits. Please do note that bits are iterated from Most significant bit (MSB)

import java.util.Iterator;

public final class BitIterator implements Iterator
{
private final byte[] array;

private int bitIndex = 0;
private int arrayIndex = 0;

public BitIterator(byte[] array)
{
this.array = array;
}


public boolean hasNext()
{
return (arrayIndex < array.length) && (bitIndex < 8);
}

public Integer next()
{
Integer val = (array[arrayIndex] >> (7 - bitIndex) & 1) == 1 ? 1 : 0;
bitIndex++;
if (bitIndex == 8)
{
bitIndex = 0;
arrayIndex++;
}
return val;
}

public String getBits(int count)
{
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < count; i++)
{
if (hasNext())
{
buffer.append(next());
}
}
return buffer.toString().trim();
}

public void remove()
{
throw new UnsupportedOperationException();
}

}

No comments:

Post a Comment