How can I perform multiplication without the '*' operator?

前端 未结 30 1513
别跟我提以往
别跟我提以往 2020-12-01 01:47

I was just going through some basic stuff as I am learning C. I came upon a question to multiply a number by 7 without using the * operator. Basically it\'s like this

<
30条回答
  •  粉色の甜心
    2020-12-01 02:19

    It's easy to avoid the '*' operator:

    mov eax, 1234h
    mov edx, 5678h
    imul edx
    

    No '*' in sight. Of course, if you wanted to get into the spirit of it, you could also use the trusty old shift and add algorithm:

    mult proc
    ; Multiplies eax by ebx and places result in edx:ecx
        xor ecx, ecx
        xor edx, edx
    mul1:
        test ebx, 1
        jz  mul2
        add ecx, eax
        adc edx, 0
    mul2:
        shr ebx, 1
        shl eax, 1
        test ebx, ebx
        jnz  mul1
    done:
        ret
    mult endp
    

    Of course, with modern processors, all (?) have multiplication instructions, but back when the PDP-11 was shiny and new, code like this saw real use.

提交回复
热议问题