如何将 64 位操作数相乘并轻松获得 128 位结果? [英] How can I multiply 64 bit operands and get 128 bit result portably?

查看:14
本文介绍了如何将 64 位操作数相乘并轻松获得 128 位结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 x64,我可以使用这个:

For x64 I can use this:

 {
   uint64_t hi, lo;
  // hi,lo = 64bit x 64bit multiply of c[0] and b[0]

   __asm__("mulq %3
	"
    : "=d" (hi),
  "=a" (lo)
    : "%a" (c[0]),
  "rm" (b[0])
    : "cc" );

   a[0] += hi;
   a[1] += lo;
 }

但我想便携地执行相同的计算.例如在 x86 上工作.

But I'd like to perform the same calculation portably. For instance to work on x86.

推荐答案

据我所知,您需要一个可移植的纯 C 实现 64 位乘法,输出到 128 位值,存储在两个 64 位值中.在这种情况下,这篇文章 声称拥有您所需要的.该代码是为 C++ 编写的.把它转成C代码不需要太多:

As I understand the question, you want a portable pure C implementation of 64 bit multiplication, with output to a 128 bit value, stored in two 64 bit values. In which case this article purports to have what you need. That code is written for C++. It doesn't take much to turn it into C code:

void mult64to128(uint64_t op1, uint64_t op2, uint64_t *hi, uint64_t *lo)
{
    uint64_t u1 = (op1 & 0xffffffff);
    uint64_t v1 = (op2 & 0xffffffff);
    uint64_t t = (u1 * v1);
    uint64_t w3 = (t & 0xffffffff);
    uint64_t k = (t >> 32);

    op1 >>= 32;
    t = (op1 * v1) + k;
    k = (t & 0xffffffff);
    uint64_t w1 = (t >> 32);

    op2 >>= 32;
    t = (u1 * op2) + k;
    k = (t >> 32);

    *hi = (op1 * op2) + w1 + k;
    *lo = (t << 32) + w3;
}

这篇关于如何将 64 位操作数相乘并轻松获得 128 位结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆