题
当我在16位汇编两个值相加,什么是打印结果到控制台的最佳方式?
目前,我有这样的代码:
;;---CODE START---;;
mov ax, 1 ;put 1 into ax
add ax, 2 ; add 2 to ax current value
mov ah,2 ; 2 is the function number of output char in the DOS Services.
mov dl, ax ; DL takes the value.
int 21h ; calls DOS Services
mov ah,4Ch ; 4Ch is the function number for exit program in DOS Services.
int 21h ; function 4Ch doesn't care about anything in the registers.
;;---CODE END---;;
我觉得DL值应为ASCII码,但我不知道如何斧头附加值成ASCII后转换。
解决方案
您基本上要除以10,打印余数(一个数位),然后与商数重复。
; assume number is in eax
mov ecx, 10
loophere:
mov edx, 0
div ecx
; now eax <-- eax/10
; edx <-- eax % 10
; print edx
; this is one digit, which we have to convert to ASCII
; the print routine uses edx and eax, so let's push eax
; onto the stack. we clear edx at the beginning of the
; loop anyway, so we don't care if we much around with it
push eax
; convert dl to ascii
add dl, '0'
mov ah,2 ; 2 is the function number of output char in the DOS Services.
int 21h ; calls DOS Services
; now restore eax
pop eax
; if eax is zero, we can quit
cmp eax, 0
jnz loophere
作为一个方面说明,你在你的代码中的错误就在这里:
mov ax, 1 ;put 1 into ax
add ax, 2 ; add 2 to ax current value
mov ah,2 ; 2 is the function number of output char in the DOS Services.
mov dl, ax ; DL takes the value.
您把2
在ah
,然后你把ax
在dl
。你可以在打印前基本废弃,另外添购ax
。
您还具有大小不匹配,因为dl
为8个位宽并ax
为16个位宽。
你应该做的是翻转的最后两行并修正尺寸不匹配:
mov ax, 1 ;put 1 into ax
add ax, 2 ; add 2 to ax current value
mov dl, al ; DL takes the value.
mov ah,2 ; 2 is the function number of output char in the DOS Services.
其他提示
刚定影@Nathan费尔曼的代码
的顺序PrintNumber proc
mov cx, 0
mov bx, 10
@@loophere:
mov dx, 0
div bx ;divide by ten
; now ax <-- ax/10
; dx <-- ax % 10
; print dx
; this is one digit, which we have to convert to ASCII
; the print routine uses dx and ax, so let's push ax
; onto the stack. we clear dx at the beginning of the
; loop anyway, so we don't care if we much around with it
push ax
add dl, '0' ;convert dl to ascii
pop ax ;restore ax
push dx ;digits are in reversed order, must use stack
inc cx ;remember how many digits we pushed to stack
cmp ax, 0 ;if ax is zero, we can quit
jnz @@loophere
;cx is already set
mov ah, 2 ;2 is the function number of output char in the DOS Services.
@@loophere2:
pop dx ;restore digits from last to first
int 21h ;calls DOS Services
loop @@loophere2
ret
PrintNumber endp
的基本算法是:
divide number x by 10, giving quotient q and remainder r
emit r
if q is not zero, set x = q and repeat
请注意,这将产生反顺序的数字,所以你可能会想更换的东西,卖场每个数字的“EMIT”的步骤,这样就可以在以后迭代反向覆盖已存储的数字。
而且,注意,为二进制数转换0和9(十进制)之间为ascii,只需添加ascii码为“0”(这是48)的数量。
mov dl, ax
这将不会作为dl
和ax
具有不同位大小工作。你想要做的是创造一个你除以10的16位值环,记得在堆栈上休息,然后继续整数除法结果的循环。当到达0的结果,清理由数字堆栈位,加入48到数字将它们转换成ASCII数字,然后打印出来。
不隶属于 StackOverflow