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?
A cleaner way would be to get rid of that hard-to-parse expression and make the code more readable.
Any decent optimising compiler will basically give you the same underlying code so it’s sometimes better to optimise for readability.