开发者

Multiplying using shifts in Assembly. But getting a way too high number out! Where am I going wrong?

I am having issues with using shifts to multiply two numbers given by the user. It asks the user to enter two integers and it is supposed to multiply them. My program works well in asking for the integers, but when it gives the product it is an astronomical number no where near being correct. Where am I going wrong? what register is it reading?

%include "asm_io.inc"
segment .data

message1 db "Enter a number: ", 0 message2 db "Enter another number: ", 0 message3 db "The product of these two numbers is: ", 0

segment .bss

input1 resd 1 input2 resd 1

segment .text Global main main: enter 0,0 pusha

mov     eax, message1   ; print out first message
call    print_string
call    read_int    ; input first number开发者_JS百科
mov     eax, [input1]


mov     eax, message2   ; print out second message
call    print_string
call    read_int    ; input second number
mov ebx, [input2]

cmp     eax, 0      ; compares eax to zero
cmp ebx, 0      ; compares ebx to zero
jnz LOOP        ; 

LOOP:

shl eax, 1

dump_regs 1 mov eax, message3 ; print out product call print_string mov ebx, eax call print_int


You are going wrong in pretty much everything besides asking for the numbers.

  • You are acting like read_int writes the read integer into input1 the first time it is called and into intput2 the second time. This is almost certainly not the case.
  • Even were that the case, you load the first number into eax and then immediately overwrite it with the address of message2.
  • Even if eax and ebx were loaded correctly with the input values, your code that is supposed to be multiplying the two is actually be doing something along the lines of "if the second number is non-zero, multiply eax by 2. Otherwise leave it alone."
  • Even were the loop arranged correctly, it would be multiplying eax by 2 to the power of ebx.
  • Then you overwrite this result with the address of message3 anyway, so none of that matters.
  • In the end, it is impossible to determine what register is getting printed from this code. Between this question and your other question, you seem to be expecting print_int to print any of eax, ebx, or ecx.


Ignoring the code you've posted, and looking strictly at how to multiply numbers (without using a multiply instruction), you do something like this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜