Suppose that I want to compute 20*10=200
using only bitwise shifting. This can easily done with
a = 20<<3 // 2^3
b = 20<<1 // 2^1
a + b // Result is 200.
Now, why if I try to do the same thing for division I get a wrong result? For instance if I try to compute 200/10
#include <stdio.h>
int main() {
int value = 200;
int a = value >> 3;
int b = value >> 1;
printf("200/10 is %d\n", (a+b));
return 0;
}
I get a 125
? What I'm doing wrong?
The comments here have done a great job explaining why this doesn't work. Here's an elaboration a bit more on why the multiplication technique does work, and why the division technique doesn't.
Let's begin with multiplication. Suppose you want to compute 200 × 10. You could compute that by evaluating 200 × (9 + 1), or 200 × (8 + 2), etc. Each of those expressions is equivalent to the original one. Using the distributive property, this means we could compute 200 × 9 + 200 × 1 to get 200 × 10, or we could compute 200 × 8 + 200 × 2 to get 200 × 10, etc.
It just so happens that multiplying by powers of two happens to be done more easily by doing bitshifts. So, for example, we could compute 200 × 10 by evaluating
200 x 10 = 200 x (8 + 2)
= 200 x 8 + 200 x 2
= (200 << 3) + (200 << 1)
Now, can we do this for division? Well, it is indeed true that 200 / 10 = 200 / (8 + 2), same as before. But unlike multiplication, in the case of 200 / (8 + 2), we don't have a distributive property, so we cannot rewrite
200 / (8 + 2) = (200 / 8) + (200 / 2).
Therefore, we can't use the reverse of the bitshifting technique to quickly do the division.