在不使用指令MUL,IMUL,SHL,SHR,LOOP的情况下将数字相乘 [英] Multiply numbers without using instructions MUL, IMUL, SHL, SHR, LOOP

查看:93
本文介绍了在不使用指令MUL,IMUL,SHL,SHR,LOOP的情况下将数字相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不使用x86汇编语言中的指令MUL,IMUL,SHL,SHR,LOOP,JMP的情况下计算乘法结果?

Is it possible to calculate result of multiplication without using instructions MUL, IMUL, SHL, SHR, LOOP, JMP in x86 assembly language?

推荐答案

是否可以在不使用x86汇编语言中的指令MUL,IMUL,SHL,SHR,LOOP,JMP的情况下计算乘法结果?

Is it possible to calculate result of multiplication without using instructions MUL, IMUL, SHL, SHR, LOOP, JMP in x86 assembly language?

是的

没有MUL,通常的方法是循环循环"SHIFT LEFT,TEST和ADD",如下所示:

Without MUL the normal approach is "SHIFT LEFT and TEST and ADD" in a loop, like this:

    result = 0;
    while(a > 0) {
        result = result << 1;
        if( a & 0x80000000 != 0) {
            result = result + b;
        }
        a = a << 1;
    }

请注意,像这样的32位整数循环最多(最多)进行32次迭代.

Note that a loop like this for 32-bit integers will have (at most) 32 iterations.

您可以用附加值替换这些班次(例如,用add eax, eax替换shl eax, 1);您可以将LOOP替换为显式循环(例如dec ecxjne next)或展开该循环(重复执行32次代码).这些替代品可能会提高性能.

You can replace these shifts with additions (e.g. shl eax, 1 replaced with add eax, eax); and you can replace LOOP with an explicit loop (e.g. dec ecx, jne next) or unroll the loop (repeat the code 32 times). These replacements will probably improve performance.

一旦您执行了无符号乘法运算,就可以将IMUL替换为将值转换为正数并使用无符号乘法运算的分支.例如.像:

Once you have unsigned multiplication, IMUL can be replaced with branches that convert the values to positive and uses unsigned multiplication. E.g. like:

    if(a < 0) {
        a = -a;
        if(b < 0) {
            b = -b
            return a*b;    // Unsigned multiplication
        } else {
            return -a*b;   // Unsigned multiplication
        }
    } else {
        if(b < 0) {
            b = -b
            return -a*b;   // Unsigned multiplication
        } else {
            return a*b;    // Unsigned multiplication
    }
}

这篇关于在不使用指令MUL,IMUL,SHL,SHR,LOOP的情况下将数字相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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