开发者

Algorithm to multiply 64-bit numbers using 32-bit unsigned integers

开发者 https://www.devze.com 2023-04-08 13:13 出处:网络
I have 64-bit numbers (63 bits + sign bit), represented as two\'s complement numbers, stored in two unsigned 32-bit integers.

I have 64-bit numbers (63 bits + sign bit), represented as two's complement numbers, stored in two unsigned 32-bit integers.

struct Long
开发者_开发知识库{
    uint32 high;
    uint32 low;
}

How can I implement a multiplication algorithm, using just 32-bit numbers, and check that the result fits in 63-bits? I want to return an error code indicating overflow if the result doesn't fit.


Generally you need 2*n bits to store the product of two n bit numbers (largest result is (2^n)^2 = 2^(2*n)), so my best idea is to split up the number into four 16-bit parts, multiply them one by one and add them together. 16 multiplications all in all, but error checking is trivial.


Have a look at the 'longlong.h' header file in the GNU MP library. I believe that a version of this header is also in the GNU C source. The macro: smul_ppmm is defined in terms of the unsigned double-word product: umul_ppmm. This gives you 32x32=>64 bit multiplication, which you might be able to use to implement 64x64=>128 bit multiplication.

0

精彩评论

暂无评论...
验证码 换一张
取 消