I want to round an integer, i, down to the nearest multiple of 4.
For example:
0 -> 0
1 -> 0
2 -> 0
3 -> 0
4 -> 4
5 -> 4
6 -> 4
7 -> 4
8 -> 8
9 -> 8
The obvious way for me to do this would be:
i = (i / 4) * 4;
But I have been criticised for using this because supposedly it is unclear, and looks like a mistake.
I am aware of the obvious alternative, bitwise shifting:
i = (i >> 2) << 2;
But I then realised that there is a different approach entirely:
(i | 3) - 3
Sample program:
#include <stdio.h>
int main(void) {
int i;
for(i = 0; i < 4*4; i++) {
printf("%d %d %d %d\n", i, (i / 4) * 4, (i >> 2) << 2, (i | 3) - 3);
}
return 0;
}
I want to know the standard way to do this, and if a modern compiler with highest optimisation will be intelligent enough to convert my code to the fastest method.
This is a matter of opinion. My opinion is that:
i = (i / 4) * 4;
is the best way. It's simple, and it obviously gives the right answer. Any other code you write, someone reading it will have to stop and think about what it's doing and whether it might have any corner cases that don't work.
One issue that may come up is what to do when i is negative. C uses "truncation towards zero", so if i is negative then this expression gives the negative of doing it on abs(i).
An equivalent way is:
i -= (i % 4);
which is also simple and clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With