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.
精彩评论