Guarantee uint8_t smaller then value

I would like to guarantee that a unsigned value is smaller then a threshold without a branch and without the modulo operator(requirement):
The algorithm with modulo:

x  = x % threshold;

The algorithm with a loop/branch:

while(x >= m)
{
  x -= m;
}

In special cases (like threshold == 8), this can be achieved by:

x = x & 0x07u;

Is there a possibility for thresholds, which are not a multiple of 2?


Source: c#

Leave a Reply