对于长度相等的两个字节数组A和B,我想找到字节数组B中设置的第一个未设置位,并返回该位的从零开始的索引或位置。我怎么能这样做?
例如:
A: 1111 0000 0101
B: 1111 0000 1010
^
答案 0 :(得分:1)
试试这个:
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;
答案 1 :(得分:0)
// Assuming you have two Byte[], arrA and arrB
for (int i = 0; i < arrA.length; i++)
if (arrA[i] != arrB[i]) return i;
答案 2 :(得分:0)
使用按位运算符。你需要XOR和SHIFT。
foreach字节 XOR B = C. 如果C!= 0,你就可以了解字节 现在找到位移1位 重复直到结果为> 1000 班次计数是您正在寻找的位置
答案 3 :(得分: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;
}
}
答案 4 :(得分:0)
使用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;