Yes, any respectable compiler should perform this optimization. Specifically, a % X
operation, where X
is a constant power of two will become the equivalent of an & (X-1)
operation.
GCC will even do this with optimizations turned off:
Example (gcc -c -O0
version 3.4.4 on Cygwin):
unsigned int test(unsigned int a) {
return a % 32;
}
Result (objdump -d):
00000000 <_test>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 8b 45 08 mov 0x8(%ebp),%eax
6: 5d pop %ebp
7: 83 e0 1f and $0x1f,%eax ;; Here
a: c3 ret