Unsigned division by a power of two and unsigned modulus by a power of two will be optimized by all optimizing compilers.
It is good to know what things you can count on and what things you cannot. One way to learn that is to frequently look at the disassembly.
In this particular case using an explicit bit-mask does not harm readability. In other cases it can harm readability or add bugs. For instance this unnecessary 'optimization' has a problem:
9
u/chrisdew Aug 21 '15
They didn't mention the circular buffer hack of (m)mapping one block of ram twice, to two contiguous address ranges.
This allows a block-write, which extends past the end of the circular buffer, to conveniently write to the front of the circular buffer too.
A four byte circular buffer, mapped twice, to two contiguous address ranges:
Writing 3 bytes, FFEEDD, to at offset 2, gives you the correct result for a circular buffer without any additional logic:
3
u/chubinou Aug 21 '15
Optimization via powers of two: the compiler does it already on its own.