问题描述
当我在 16 位汇编中添加两个值时,将结果打印到控制台的最佳方法是什么?
When I add two values in 16 bit assembly, what is the best way to print the result to console?
目前我有这个代码:
;;---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 码,但我不确定如何将加法后的 ax 值转换为 ASCII.
I think that dl value should be in ASCII code, but I'm not sure how to convert ax value after addition into ASCII.
推荐答案
你基本上想除以 10,打印余数(一位),然后用商重复.
You basically want to divide by 10, print the remainder (one digit), and then repeat with the quotient.
; 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
作为旁注,您的代码中有一个错误:
As a side note, you have a bug in your code right here:
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
之前把它弄乱了.
You put 2
in ah
, and then you put ax
in dl
. You're basically junking ax
before printing it.
由于 dl
是 8 位宽而 ax
是 16 位宽,因此您也有大小不匹配.
You also have a size mismatch since dl
is 8 bits wide and ax
is 16 bits wide.
你应该做的是翻转最后两行并修复大小不匹配:
What you should do is flip the last two lines and fix the size mismatch:
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.
这篇关于在 x86 程序集中将整数打印到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!