Java Iterate Bits in Byte Array

前端 未结 7 1560
夕颜
夕颜 2020-12-08 02:49

How can i iterate bits in a byte array?

7条回答
  •  再見小時候
    2020-12-08 03:00

    You'd have to write your own implementation of Iterable which took an array of bytes, and then created Iterator 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...

提交回复
热议问题