组装,打印ASCII码 [英] Assembly, printing ascii number
问题描述
我的汇编代码有问题.我想打印存储在寄存器 cx 中的数字,但是当我尝试打印它时,它打印的是 ascii 字符而不是 ascii 数字,所以我决定编写一个程序将 ascii 字符转换为 ascii 值.问题是,当我尝试调用该过程时,程序会冻结,我必须重新启动 dosbox.有谁知道这段代码有什么问题?谢谢.
I have a problem with my assembly code. I want to print number stored in register cx, but when i tried to print it, it printed ascii character instead of ascii number, so I decided to write a procedure to convert ascii char to ascii value. Problem is, that when I try to call that procedure, the program freezes and I have to restart dosbox. Does anyone know whats wrong with this code? Thanks.
P4 PROC
MOV AX,CX ;CX = VALUE THAT I WANT TO CONVERT
MOV BX,10
ASC2:
DIV BX ;DIV AX/10
ADD DX,48 ;ADD 48 TO REMAINDER TO GET ASCII CHARACTER OF NUMBER
PUSH AX ;SAVE AX
MOV AH,2 ;PRINT REMAINDER STORED IN DX
INT 21H ;INTERRUP
POP AX ;POP AX BACK
CMP AX,0
JZ EXTT ;IF AX=0, END OF THE PROCEDURE
JMP ASC2 ;ELSE REPEAT
EXTT:
RET
P4 ENDP
推荐答案
这样的方法更适合打印十进制值(新代码为小写):
Something like this would work better for printing a decimal value (the new code is in lowercase):
mov byte [buffer+9],'$'
lea si,[buffer+9]
MOV AX,CX ;CX = VALUE THAT I WANT TO CONVERT
MOV BX,10
ASC2:
mov dx,0 ; clear dx prior to dividing dx:ax by bx
DIV BX ;DIV AX/10
ADD DX,48 ;ADD 48 TO REMAINDER TO GET ASCII CHARACTER OF NUMBER
dec si ; store characters in reverse order
mov [si],dl
CMP AX,0
JZ EXTT ;IF AX=0, END OF THE PROCEDURE
JMP ASC2 ;ELSE REPEAT
EXTT:
mov ah,9 ; print string
mov dx,si
int 21h
RET
buffer: resb 10
不是直接打印每个字符,而是以相反的顺序将字符添加到缓冲区.对于值 123,它将在缓冲区 [8] 处添加 '3',在缓冲区 [7] 处添加 '2',在缓冲区 [6] 处添加 '1' - 因此,如果您随后打印从缓冲区 + 6 开始的字符串,您将得到123".
我使用的是 NASM 语法,但希望它应该足够清楚.
Instead of printing each character directly it adds the characters to a buffer in reverse order. For the value 123 it would add '3' at buffer[8], '2' at buffer[7] and '1' at buffer[6] - so if you then print the string starting at buffer+6 you get "123".
I'm using NASM syntax but hopefully it should be clear enough.
这篇关于组装,打印ASCII码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!