Java Iterate Bits in Byte Array Java Iterate Bits in Byte Array arrays arrays

Java Iterate Bits in Byte Array


You'd have to write your own implementation of Iterable<Boolean> which took an array of bytes, and then created Iterator<Boolean> values which remembered the current index into the byte array and the current index within the current byte. Then a utility method like this would come in handy:

private static Boolean isBitSet(byte b, int bit){    return (b & (1 << bit)) != 0;}

(where bit ranges from 0 to 7). Each time next() was called you'd have to increment your bit index within the current byte, and increment the byte index within byte array if you reached "the 9th bit".

It's not really hard - but a bit of a pain. Let me know if you'd like a sample implementation...


public class ByteArrayBitIterable implements Iterable<Boolean> {    private final byte[] array;    public ByteArrayBitIterable(byte[] array) {        this.array = array;    }    public Iterator<Boolean> iterator() {        return new Iterator<Boolean>() {            private int bitIndex = 0;            private int arrayIndex = 0;            public boolean hasNext() {                return (arrayIndex < array.length) && (bitIndex < 8);            }            public Boolean next() {                Boolean val = (array[arrayIndex] >> (7 - bitIndex) & 1) == 1;                bitIndex++;                if (bitIndex == 8) {                    bitIndex = 0;                    arrayIndex++;                }                return val;            }            public void remove() {                throw new UnsupportedOperationException();            }        };    }    public static void main(String[] a) {        ByteArrayBitIterable test = new ByteArrayBitIterable(                   new byte[]{(byte)0xAA, (byte)0xAA});        for (boolean b : test)            System.out.println(b);    }}


Original:

for (int i = 0; i < byteArray.Length; i++){   byte b = byteArray[i];   byte mask = 0x01;   for (int j = 0; j < 8; j++)   {      bool value = b & mask;      mask << 1;   }}

Or using Java idioms

for (byte b : byteArray ) {  for ( int mask = 0x01; mask != 0x100; mask <<= 1 ) {      boolean value = ( b & mask ) != 0;  }}