简体   繁体   中英

algorithm to multiply 64 bit numbers using 32 bit unsigned 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM