/* Implementation of an algorithm to multiply two 16-bit signed integers using the same method as ``by hand''. The sign of the result is first determined and the multiplication is then performed on the absolute values of the operands. Author: Frédéric Goualard Last modified: 2022-11-02/09:07:26/+0100 */ #include #include int16_t multiply(int16_t a, int16_t b) { uint16_t ua = (uint16_t)a; uint16_t ub = (uint16_t)b; uint16_t sign = 0; if (ua & (1<<15)) { // a<0 ? sign = 1; ua = ~ua + 1; } if (ub & (1<<15)) { // b<0 ? sign = sign ^ 1; ub = ~ub + 1; } uint16_t res = 0; uint16_t mask = 1; while (mask != (1<<15)) { if ((ub & mask) != 0) { res = res + ua; } ua = ua + ua; mask = mask + mask; } if (sign) { return (int16_t)(~res + 1); } else { return (int16_t)res; } } int main(void) { { int16_t a = -56; int16_t b = 13; printf("%d x %d = %d\n",a,b,multiply(a,b)); } { int16_t a = -61; int16_t b = -13; printf("%d x %d = %d\n",a,b,multiply(a,b)); } }