ccomparisonbit-manipulationequalitybranchless

Test if fixed set is equal without branching


I have a set of integers (x, y, z) and a function that takes 3 integers (u, v, w). How can I test if (x,y,z) == (u,v,w)? The naive way is:

bool match = (x == u || x == v || x == w) && (y == u || y == v || y == w) && (z == u || z == v || z == w);

Does anyone know of some smart bit operations/arithmetic to do the same thing?

I can assume that neither (x, y, z) or (u, v, w) contain duplicates.


Solution

  • In this case, you can replace the logical operations by bitwise operations to eliminate the branching:

    bool match = (x == u | x == v | x == w)
               & (y == u | y == v | y == w)
               & (z == u | z == v | z == w);
    

    However, you would have to measure the performance effect to see if this is faster or slower.