Hacker News new | ask | show | jobs
by caf 3478 days ago
Modulo by a constant doesn't require a division, you can instead use multiplications, shifts, adds and subtracts. This transform is typical for compilers. For example, this is what gcc targetting x86_64 does to perform % 17 on the unsigned value in %edi:

  movl	$-252645135, %edx
  movl	%edi, %eax
  mull	%edx
  movl	%edx, %eax
  shrl	$4, %eax
  movl	%eax, %edx
  sall	$4, %edx
  addl	%edx, %eax
  subl	%eax, %edi
2 comments

It doesn't require division, but how is that long sequence of instructions going to beat an AND?
That only works for compile time constants, though. With a power of two sized buffer you can just store the mask and decide how large you want your buffer to be at runtime.
libdivide (http://libdivide.com) implements similar logic at runtime
You can also compute the optimization at runtime, same as the compiler does. Libtheora contains code for this, used for quantizing video data.