Reputation: 465
I am working on a programme to calculate 2^p using the traditional school arithmetic technique, multiply by 2, carry 1 if > 9. I have written two lines of code that return n / 10 and n % 10 using bitwise operators. These are accurate for 0 - 19 inclusive, which is all that is needed when the multiplier is 2: the largest number is (2 * 9) + 1. However this method is inaccurate from 20 onwards and not needed. These techniques speed up the programme.
Because I would like to be certain I am using C correctly, is this technique good practice?
#include <stdio.h>
int main(void) {
unsigned int d, m;
/* division by 10 */
for (int i=0; i<20; ++i) {
d = (i + 6) >> 4;
printf("%u ", d);
}
printf("\n");
/* modulus 10 */
for (int i=0; i<20; ++i) {
m = i - (((i + 6) >> 4) * 10);
printf("%u ", m);
}
printf("\n");
return 0;
}
Upvotes: 0
Views: 388
Reputation: 155683
This is not good practice.
If you compile code that divides or modulos by constants, and enable optimizations, the compiler will do this for you when it's possible and equivalent (on checking, gcc uses a somewhat more complicated set of imul
, shifts and a subtraction rather than an integer division instruction; more expensive than what you wrote, but still much cheaper than integer division). And your code won't be an unreadable mess, that breaks when passed values even slightly outside its design parameters.
There are extremely rare cases where you might do something like this, if:
But outside of that case, you never want to write unreadable, unmaintainable, brittle code just to shave a few cycles.
Upvotes: 2