2009-06-23 67 views
31

如何迭代字節數組中的位?字節數組中的Java迭代位

+0

你不能。至少不是直接的。你想做什麼,也許有更好的方法。一個字節數組包含一組字節。 – OscarRyz 2009-06-23 19:03:41

+15

再一次,我希望java.util.BitSet有一個byte []構造函數。 – 2009-06-23 19:05:21

+0

它可以做到。我會用Jon Skeet的方法去投票。但是,在大多數情況下,使用位時,有一些花式的按位運算符可以使您的任務更快。如果你告訴我們你想要做什麼,那麼我們可能會幫助你找到比迭代比特更好的方法。 – StriplingWarrior 2009-06-23 19:31:31

回答

40

你必須編寫自己的執行Iterable<Boolean>歷時字節數組,然後創建Iterator<Boolean>值該記住當前索引字節數組當前字節中的當前索引。然後這樣一個工具方法會派上用場:

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

(其中從0 bit範圍至7)。每次調用next()時,都必須在當前字節內增加位索引,並在達到「第9位」時增加字節數組內的字節索引。

這不是真的 - 但有點痛苦。讓我知道你是否想要一個示例實現...

0

你可以遍歷字節數組,並且對於每個字節使用按位運算符遍歷它的位。

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; 
    } 
} 

或者使用Java成語

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

我需要一些位在我的應用程序流。 Here你可以找到我的BitArray實現。它不是一個真正的迭代器模式,但您可以以流方式從數組中請求1-32位。稍後在文件中還有一個稱爲BitReader的替代實現。

2

另一種方法是使用一個BitInputStream一樣,你可以找到here,寫這樣的代碼:

BitInputStream bin = new BitInputStream(new ByteArrayInputStream(bytes)); 
    while(true){ 
     int bit = bin.readBit(); 
     // do something 
    } 
bin.close(); 

(注:代碼中不包含EOFException類或IOException異常處理爲簡潔)

但我會和Jon Skeets一起去做,並且自己做。

2

我知道,可能不是「最酷」的方法,但可以使用下面的代碼提取每一位。

int n = 156; 

String bin = Integer.toBinaryString(n); 
System.out.println(bin); 

char arr[] = bin.toCharArray(); 
for(int i = 0; i < arr.length; ++i) { 
    System.out.println("Bit number " + (i + 1) + " = " + arr[i]); 
} 

位號1 = 1

位號2 = 0

位號3 = 0

位號4 = 1

位號5 = 1

位號6 = 1

位號7 = 0

位編號8 = 0

16
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); 
    } 
}