Java迭代字节数组中的位

Ham*_*aya 32 java arrays byte loops bit

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

Jon*_*eet 42

您必须编写自己的实现,Iterable<Boolean>其中包含一个字节数组,然后创建Iterator<Boolean>值,记住当前索引到字节数组当前字节中的当前索引.那么像这样的实用方法会派上用场:

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

(bit范围从0到7).每次next()调用时,您必须在当前字节中递增位索引,并在达到"第9位"时增加字节数组中的字节索引.

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


Mat*_*hen 17

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Pau*_*ier 9

原版的:

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;
   }
}
Run Code Online (Sandbox Code Playgroud)

或使用Java习语

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

  • 如果我不得不猜测,我会说C#. (3认同)