Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying two 32 bit numbers without using 64 bit int

We are doing some 32bit * 32bit multiplication using the following algorithm

Let us we want to multiply a (32 bit) with b (32 bit), both signed,

a = ah * 2^16 + al [ah - Higher 16 bits, al - Lower 16 bits]

b = bh * 2^16 + bl [bh - Higher 16 bits, bl - Lower 16 bits]

We are effectively doing

Result = (al * bl) + (((ah * bl) + (al * bh)) * 2^16) + ((ah * bh) * 2 ^ 32) ~~~


My question,

Is their any better way to do this?

like image 931
Alphaneo Avatar asked Feb 21 '26 23:02

Alphaneo


1 Answers

In any mainstream compiler, the emulation of 64-bit ints on a 32-bit platform will be about as efficient as doing the mutli-step math yourself. But it will be much more reliably correct.

When doing simple arithmetic with values large enough to overflow, even the most highly tuned math library that I've seen just uses int64.

like image 175
Alan Avatar answered Feb 24 '26 01:02

Alan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!