My problem is this: I have the value x and the pattern p both variables of the same size. The goal is to iterate over all bit patterns x that are not masked by p.
Example: if we have p = 1001 , we want to find 0000 , 0001 , 1000 and 1001 - not necessarily in that order.
The standard implementation is in C99 (a return value indicates whether we returned all values):
static bool next(size_t val, size_t mask, size_t *out) { if (val == mask) { return false; } size_t current = val & mask; size_t inc = 1; size_t new_val = current + inc; while ((new_val & mask) <= current) { inc++; new_val = current + inc; } *out = new_val; return true; }
I would have thought there should be some trick to make this more efficient, but I can’t find any big improvements (other than calculating the trailing zeros of the mask and setting the initial value of inc accordingly, which isn’t a big part of the improvement).
Edit: It is also important that for each generated value a lot of additional work is generated, which means that a lot of duplicates are out of the question (some duplicates, even if they are not recognized, will be fine, there are no side effects to the work done, this just slowdown).
optimization c algorithm bit-manipulation
Voo
source share