Compare between byte

  • Thread starter Thread starter chris chan
  • Start date Start date
C

chris chan

Is there any way to compare two byte by XOR in a fast way
and return the number of bits is equal .

e.g.
b1 = 11100011
b2 = 01010010

after XOR compare will return 4 bit is equal
 
Sorry,

for ( byte i = 0; i < 7; ++i )
should be
for ( byte i = 0; i < 8; ++i )

Regards

Chris Taylor

Chris Taylor said:
Hi,

I think the following function should help you achieve what you want. It
will count the number of bits that any integer, type up to a int for this
example, that they have in common.

byte countCommonBits( byte b1, byte b2 )
{
byte nCount = 0;

for ( byte i = 0; i < 7; ++i )
{
bool r1 = ( b1 & 1 ) == 1;
bool r2 = ( b2 & 1 ) == 1;
if ( r1 == r2 )
++nCount;
b1 >>= 1;
b2 >>= 1;
}

return nCount;
}


It works by check bit 0 of both byte, if they are the same then nCount is
incremented. Then the bit 1 is shifted into position 0 and the test is
repeated. This is done for all 8 bits of the byte datatype.

Hope this helps

Chris Taylor
 
thx for your reply
i will have a try ^_^

--


Chris Taylor said:
Sorry,

for ( byte i = 0; i < 7; ++i )
should be
for ( byte i = 0; i < 8; ++i )

Regards

Chris Taylor
 
If performance is important, it would probably be faster to us a
static lookup table instead of calculating the number of bits on each
call.

static int[] OnesInByte = new int[] {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8,
};


int countCommonBits( byte b1, byte b2 )
{
return OnesInByte[b1 & b2];
}



Mattias
 
Back
Top