0

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?

For example:

A: 1111 0000 0101
B: 1111 0000 1010
             ^
3
  • if the arrays are long-length, you may need to get some hand of threads, or even gpu. Commented Apr 6, 2014 at 21:30
  • Why do you have an array of byte? Why not two int variables that each have various bits set? Commented Apr 6, 2014 at 21:36
  • Byte[] is faster than BitSet. Commented Apr 6, 2014 at 21:39

5 Answers 5

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;
Sign up to request clarification or add additional context in comments.

1 Comment

You could use int j = Integer.numberOfTrailingZeros(x) to replace the whole innermost loop. It compiles down to one instruction on most platforms.
0
// Assuming you have two Byte[], arrA and arrB
for (int i = 0; i < arrA.length; i++)
    if (arrA[i] != arrB[i]) return i;

Comments

0

Using the bitwise operator. You need XOR and 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

Comments

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

Comments

0

A possible solution using 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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.