整数分割乘法 [英] Split Multiplication of integers

查看:144
本文介绍了整数分割乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用两个32位整数作为参数的算法,并返回这些参数的乘法分成另外两个32位整数:32最高位部和32个最低位部

我会尝试:

  uint32_t的P1,P2; //全局变量来保存结果

无效MULT(uint32_t的X,uint32_t的Y){
    uint64_t中R =(X * Y);

    P1 = R>> 32;
    P2 = R&安培; 0xFFFFFFFF的;

}
 

虽然它的工作原理 1 ,它不能保证的64位整数的机器的存在,既不是利用他们的编译器。

那么,如何解决这个问题的最好方法是什么?


注意 1 :事实上,它没有工作,因为我的编译器不支持64位整数

观测:请,避免使用提升

解决方案

只需使用16位数字。

 无效乘法(uint32_t的一个,uint32_t的B,uint32_t的* H,uint32_t的* 1){
    uint32_t的常量基地= 0x10000的;
    uint32_t的人=一%的基础啊= A /基地,BL = B%的基础上,BH = B /基地;
    * L = A * BL;
    * H =啊* BH;
    uint32_t的RLH = * L /基地+人* BH;
    * H + = RLH /基地;
    RLH = RLH%基地+啊* BL;
    * H + = RLH /基地;
    * L =(RLH%的基础)*基地+ * 1%的基础;
}
 

I need an algorithm that uses two 32-bit integers as parameters, and returns the multiplication of these parameters split into two other 32-bit integers: 32-highest-bits part and 32-lowest-bits part.

I would try:

uint32_t p1, p2; // globals to hold the result

void mult(uint32_t x, uint32_t y){
    uint64_t r = (x * y);

    p1 = r >> 32;
    p2 = r & 0xFFFFFFFF;

}

Although it works1, it's not guaranteed the existence of 64-bit integers in the machine, neither is the use of them by the compiler.

So, how is the best way to solve it?


Note1: Actually, it didn't work because my compiler does not support 64-bit integers.

Obs: Please, avoid using boost.

解决方案

Just use 16 bits digits.

void multiply(uint32_t a, uint32_t b, uint32_t* h, uint32_t* l) {
    uint32_t const base = 0x10000;
    uint32_t al = a%base, ah = a/base, bl = b%base, bh = b/base;
    *l = al*bl;
    *h = ah*bh;
    uint32_t rlh = *l/base + al*bh;
    *h += rlh/base;
    rlh = rlh%base + ah*bl;
    *h += rlh/base;
    *l = (rlh%base)*base + *l%base;
}

这篇关于整数分割乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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