Multiply numbers without using instructions MUL, IMUL, SHL, SHR, LOOP

后端 未结 4 451
误落风尘
误落风尘 2021-01-22 04:33

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

4条回答
  •  鱼传尺愫
    2021-01-22 05:30

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

    Yes.

    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;
        }
    

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

    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.

    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
        }
    }
    

提交回复
热议问题