I challenged myself to implement multiplication of signed integers using only +
, -
, >>
, <<
, &
, |
, ^
, and conditionals, though I would like to improve my method to not use conditionals if possible in the future. Any input would be very helpful.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#include <time.h>
int multiply(int, int);
int main() {
int a, b, c, i;
bool equal;
srand(time(NULL));
for (i = 0; i < 100; i++) {
// 0x8000 to ensure no integer overflow is possible
a = (rand() % 0x8000) * (rand() % 2 ? -1 : 1);
b = (rand() % 0x8000) * (rand() % 2 ? -1 : 1);
c = multiply(a, b);
equal = (c == a * b);
printf("%-11d * %-11d = %-11d (%s)\n", a, b, c, (equal ? "Success" : "Failure"));
if (!equal) {
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
int multiply(int a, int b) {
struct {
unsigned char index : 5;
} bit;
int c = INT_MAX & a, // remove sign bit
d = INT_MAX & b,
sign = (INT_MIN & a) ^ (INT_MIN & b), // sign of product
mask = 0x40000000,
prod = 0;
bit.index = 30; // keeping track of mask bit index
do {
prod += (mask & c ? d << bit.index : 0);
} while ((bit.index--) && (mask >>= 1));
return sign | (prod & INT_MAX);
}