q_mul(int16_t a, int16_t b) { int16_t result; int32_t temp; temp = (int32_t)a * (int32_t)b; // result type is operand's type // Rounding; mid values are rounded up temp += K; // Correct by dividing by base and saturate result result = sat16(temp >> Q); return result; } Division int16_t q_div(int16_t a, int16_t b) { /* pre-multiply by the base (Upscale to Q16 so that the result will be in Q8 format) */ int32_t temp = (int32_t)a << Q; /* Rounding: mid values are rounded up (down for negative values). */ /* OR compare most significant bits i.e. if (((temp >> 31) & 1) == ((b >> 15) & 1)) */ if ((temp >= 0 && b >= 0) || (temp < 0 && b < 0)) { temp += b / 2; /* OR shift 1 bit i.e. temp += (b >> 1); */ } else { temp -= b / 2; /* OR shift 1 bit i.e. temp -= (b >> 1); */ } return (int16_t)(temp / b); } See also Binary scaling Fixed-point arithmetic Floating-point arithmetic References Further reading (Note: the accuracy of the article is in dispute; see discussion.) External links Computer arithmetic