Computing high 64 bits of a 64x64 int product in C

前端 未结 5 1630
面向向阳花
面向向阳花 2020-12-17 16:26

I would like my C function to efficiently compute the high 64 bits of the product of two 64 bit signed ints. I know how to do this in x86-64 assembly, with imulq and pullin

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 16:48

    The general answer is that x * y can be broken down into (a + b) * (c + d), where a and c are the high order parts.

    First, expand to ac + ad + bc + bd

    Now, you multiply the terms as 32 bit numbers stored as long long (or better yet, uint64_t), and you just remember that when you multiplied a higher order number, you need to scale by 32 bits. Then you do the adds, remembering to detect carry. Keep track of the sign. Naturally, you need to do the adds in pieces.

    For code implementing the above, see my other answer.

提交回复
热议问题