Bitwise operations are prolific and efficient.
I crafted a test file using bitwise (the - below) and your modular division method (+ below). The difference in assembly is shown in a diff below:
- and w8, w8, w9
+ sdiv w8, w8, w9
+ mov w10, #2
+ sdiv w9, w8, w10
+ mul w9, w9, w10
+ subs w8, w8, w9
In the test, I performed the operations one trillion two hundred eighty billion times. Here are the times with x1 being bitwise and x2 being modular division:
% time ./x1 ; time ./x2
18328383850248350848
5.174u 0.031s 0:05.31 97.9% 0+0k 0+0io 0pf+0w
12690158593672146048
6.440u 0.037s 0:06.53 99.0% 0+0k 0+0io 0pf+0w
I ran this test many times, and found the results are similar. The bitwise is about 1 1/2 second faster.
Do you need to worry about the performance of this operation on modern computers?
No.
Hasty Benchmark - not scientific
int main() {
int a = INT_MAX/16, i;
unsigned long b;
for (; a > 0; a--) {
for (i = 0; i < 32; i++) {
b += a & (1 << i);
}
}
printf("%lu\n", b);
}