Skip to content

Instantly share code, notes, and snippets.

@ljmccarthy
Created August 20, 2024 10:55
Show Gist options
  • Save ljmccarthy/86dad4a31d1913c09cd1cd87d88103d7 to your computer and use it in GitHub Desktop.
Save ljmccarthy/86dad4a31d1913c09cd1cd87d88103d7 to your computer and use it in GitHub Desktop.
Multiply using addition and shift
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
uint32_t umul32(uint32_t a, uint32_t b)
{
if (a < b) {
uint32_t tmp = a;
a = b;
b = tmp;
}
uint32_t result = 0;
while (b) {
result += (b & 1) ? a : 0;
a <<= 1;
b >>= 1;
}
return result;
}
int32_t imul32(int32_t a, int32_t b)
{
if (a < 0) {
a = -a;
b = -b;
}
if (b < 0) {
a = -a;
b = -b;
}
return umul32((uint32_t)a, (uint32_t)b);
}
int main()
{
for (uint32_t i = 0; i <= 100; i++) {
for (uint32_t j = 0; j <= 10; j++) {
uint32_t result = umul32(i, j);
printf("%d * %d = %d\n", i, j, result);
assert(result == i * j);
}
}
for (int32_t i = -100; i <= 100; i++) {
for (int32_t j = -100; j <= 100; j++) {
int32_t result = imul32(i, j);
printf("%d * %d = %d\n", i, j, result);
assert(result == i * j);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment