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.
source to share
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)
source to share
Like everyone else, use XOR to determine what is different and then use one of those algorithms to count .
source to share
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 .
source to share