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.

+2


source to share


7 replies


Take the XOR of two fields and count the number of results.



+11


source


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)

+5


source


Like everyone else, use XOR to determine what is different and then use one of those algorithms to count .

+4


source


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

      

+3


source


XOR numbers, then the problem becomes a matter of counting the 1s in the result.

+1


source


In Java:

Integer.bitCount(a ^ b)

      

+1


source


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 .
0


source







All Articles