Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick bitwise comparison

I have two bytes that are made up of two 4-bit numbers packed together. I need to know if either of the two numbers from the first byte matches either of the numbers from the second byte. Zero is considered null and shouldn't match itself.

Obviously, I can do this by unpacking the numbers and comparing them one by one:

a = 0b10100101;
b = 0b01011111; // should have a match because 0101 is in both

a1 = a>>4; a2 = a&15;
b1 = b>>4; b2 = b&15;

return (a1 != 0 && (a1 == b1 || a1 == b2)) || (a2 != 0 && (a2 == b1 || a2 == b2));

//     ( true   && (  false  ||   false )) || ( true   && (  true   ||   false ))
//     ( true   &&         false         ) || ( true   &&         true          )
//            false                        ||         true
//                                        TRUE

However I'm just wondering if anyone knows of a cleaner way to do this?

like image 903
Niet the Dark Absol Avatar asked Nov 04 '22 17:11

Niet the Dark Absol


1 Answers

Precompute the answer and store it in a lookup table. The key to your table is 16 bits ((a<<8)+b). It need only be 1 bit output (uses 8K), but you could use 8 bits for simplicity (uses 64K).

like image 155
Keith Randall Avatar answered Nov 15 '22 17:11

Keith Randall