Integer Mod Optimization

On most architectures, integer divide is a relatively expensive instruction. Power-of-two integer modulus expressions can be replaced with conditional and shift instructions to avoid the divide and multiply and increase run-time performance.

Example:

In the function below, the power-of-two integer modulus expression (x % 8) can be replaced with faster instructions.

int f (int x)
{
  return x % 8;
}
  

The code fragment below shows the function after the modulus expression has been optimized.

int f (int x)
{
  int temp = x & 7;
  return (x < 0) ? ((temp == 0) ? 0 : (temp | ~7)) : temp;
}