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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With