How can I check if two bit patterns are different in any N bits (position doesn't matter)
Let's say I have this bitfield value: 10101001
How can I check if some other value is different in any bits n
. Excluding position?
Example:
10101001
10101011 --> 1 bit different
10101001
10111001 --> 1 bit different
10101001
01101001 --> 2 bits different
10101001
00101011 --> 2 bits different
I need to do a lot of such comparisons, so I'm looking for a job first, but any hint is greatly appreciated.
Take the XOR of two fields and count the number of results.
if you XOR 2 values โโtogether, you are only left with the bits that differ.
You only need to count the bits that are still 1 and you have the answer
in c:
unsigned char val1=12;
unsigned char val2=123;
unsigned char xored = val1 ^ val2;
int i;
int numBits=0;
for(i=0; i<8; i++)
{
if(xored&1) numBits++;
xored>>=1;
}
although there are probably faster ways to count the bits in a byte (you could, for example, use a lookup table for 256 values)
Like everyone else, use XOR to determine what is different and then use one of those algorithms to count .
This gets the bit difference between the values โโand counts three bits at a time:
public static int BitDifference(int a, int b) {
int cnt = 0, bits = a ^ b;
while (bits != 0) {
cnt += (0xE994 >> ((bits & 7) << 1)) & 3;
bits >>= 3;
}
return cnt;
}
XOR numbers, then the problem becomes a matter of counting the 1s in the result.
In Java:
Integer.bitCount(a ^ b)
The comparison is done with XOR, as others have already answered.
counting can be done in several ways:
- left shift and addition.
- search in the table.
- which you can find using Karnot maps .