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

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


For two byte arrays A and B of equal length, I'd like to find the first unset bit in byte array A that is set in byte array B, and return the zero-based index or position of that bit. How can I do so?

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

For example:

例如:

A: 1111 0000 0101
B: 1111 0000 1010
             ^

5 个解决方案

#1


1  

Try this:

嘗試這個:

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;

#2


0  

// Assuming you have two Byte[], arrA and arrB
for (int i = 0; i < arrA.length; i++)
    if (arrA[i] != arrB[i]) return i;

#3


0  

Using the bitwise operator. You need XOR and SHIFT.

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

foreach bytes do A XOR B = C if C != 0 you fine the byte now to find the bit shift left 1 bit repeat until the result is > 1000 the shift count is the bit position you're looking for

foreach bytes do A XOR B = C如果C!= 0你現在對字節進行罰款以找到位移1位重復,直到結果大於1000,移位計數是你正在尋找的位位置

#4


0  

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

#5


0  

A possible solution using BitSet:

使用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;

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/04/06/7255e3380f85c7ee22fafd4ba766014c.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com