簡體   English   中英

在Java中,如何迭代兩個字節數組的位?

[英]In Java, how do you iterate over the bits of two byte arrays?

對於長度相等的兩個字節數組A和B,我想找到字節數組B中設置的字節數組A中的第一個未設置位,然后返回該位的從零開始的索引或位置。 我該怎么辦?

例如:

A: 1111 0000 0101
B: 1111 0000 1010
             ^

嘗試這個:

int length = A.length<B.length? A.length:B.length;
for (int i=0; i<length; i++)
{
    int x = A[i]^B[i];
    if (x != 0)
    {
        for (int j=0; true; j++)
        {
            if ((x&1) == 1)
                return Byte.SIZE*i+j;
            x >>= 1;
        }
    }
}
return -1;
// Assuming you have two Byte[], arrA and arrB
for (int i = 0; i < arrA.length; i++)
    if (arrA[i] != arrB[i]) return i;

使用按位運算符。 您需要XOR和SHIFT。

foreach字節執行A XOR B = C如果C!= 0,則現在對字節進行細化以找到左移一位的重復,直到結果> 1000為止,移位計數是您要查找的位位置

Byte[] arrA;
Byte[] arrB;

/* Initializing arrays - Setting same lengths etc... */

for (int i = 0; i < arrA.length; i++){
    if (arrA[i]==0 && arrB[i]==1){ 
      return i;
    }
}

使用BitSet的可能解決方案:

BitSet A = BitSet.valueOf(new long[] { Integer.valueOf("111100000101", 2) });
BitSet B = BitSet.valueOf(new long[] { Integer.valueOf("111100001010", 2) });

A.xor(B); // A holds bits that are in the set state only for A or only for B
int index = A.length() + 1;
while ((index = A.previousSetBit(index - 1)) > 0) {  // starting from the end going backward
    if (B.get(index)) {
        // if the corresponding bit in B is in the set state then the bit in A is not set
        break;
    }
}
// index is the zero-based index of the first unset bit in byte array A that is set in byte array B,
return index;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM