Multiplication
// precomputed value:
#define K (1 << (Q-1))
signed int a, b, result;
signed long int temp;
temp = (long int) a * (long int) b; // result type is operand's type
// Rounding; mid values are rounded up
temp += K;
// Correct by dividing by base
result= temp >> Q;
[edit]
Division
signed int a,b,result;
signed long int temp;
// pre-multiply by the base
temp = (long int)a << Q;
// So the result will be rounded ; mid values are rounded up.
temp = temp+b/2;
result = temp/b; |