Java 迭代字节数组中的位

2022-09-01 06:33:06

如何迭代字节数组中的位?


答案 1

您必须编写自己的实现,该实现需要一个字节数组,然后创建将当前索引记住到字节数组中的值当前字节中的当前索引的值。然后,像这样的实用程序方法将派上用场:Iterable<Boolean>Iterator<Boolean>

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

(范围从 0 到 7)。每次调用时,您都必须在当前字节内递增位索引,如果达到“第9位”,则必须在字节数组内递增字节索引。bitnext()

这并不 - 但有点痛苦。如果您想要一个示例实现,请告诉我...


答案 2
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);
    }
}