简体   繁体   English

程序集8086循环问题

[英]Assembly 8086 loops issue

The pseudocode is the following: 伪代码如下:

read c        //a double digit number
for(i=1,n,i++)
{ if (n%i==0)
     print i;}

In assembly I have written it as: 在汇编中我把它写成:

mov bx,ax   ;  ax was the number  ex.0020, storing a copy in bx.

mov cx,1    ; the start of the for loop
.forloop:
mov ax,bx   ; resetting ax to be the number(needed for the next iterations)
div cx
cmp ah,0    ; checking if the remainder is 0 
jne .ifinstr
add cl 48    ;adding so my number would be displayed later as decimal
mov dl,cl   ;printing the remainder
mov ah,2
int 21h
sub cl,48   ;converting it back to hexa
.ifinstr:
inc cx      ;the loop goes on
cmp cx,bx
jle .forloop

I've checked by tracing its steps. 我已经通过追踪它的步骤进行了检查。 The first iteration goes well, then, at the second one, it makes ax=the initial number and cx=2 as it should, but at 'div cx' it jumps somwhere unknown to me and it doesn't stop anywhere. 第一次迭代顺利进行,然后,在第二次迭代中,它使ax =初始数字和cx = 2,但是在'div cx'它会跳到我不知道的地方并且它不会停在任何地方。 It does: 它确实:

push ax
mov al,12
nop
push 9
.
.

Any idea why it does that? 知道为什么会这样吗?

try to do mov dx,0 just before div instruction. 尝试在div指令之前执行mov dx,0。 Basically every time you come after jump, there may be some data in dx register, so you can just move zero in dx or XOR dx,dx. 基本上每次跳转后,dx寄存器中都可能有一些数据,所以你可以在dx或XOR dx,dx中移动零。 This is to be done, because otherwise division will be considered differently. 这是要做的,因为否则划分将被视为不同。 See this: Unsigned divide. 见:无符号除法。

Algorithm: 算法:

when operand is a byte:
AL = AX / operand
AH = remainder (modulus) 

when operand is a word:
AX = (DX AX) / operand
DX = remainder (modulus) 

Example: 例:

MOV AX, 203 ; MOV AX,203; AX = 00CBh MOV BL, 4 DIV BL ; AX = 00CBh MOV BL,4 DIV BL; AL = 50 (32h), AH = 3 RET AL = 50(32h),AH = 3 RET

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM