【问题标题】:How can I convert a variable to a DECIMAL string to print?如何将变量转换为 DECIMAL 字符串以进行打印?
【发布时间】:2011-10-22 22:40:09
【问题描述】:

我打算将 X 变量转换为十进制。我在使用 turbo assembler 时遇到了困难,你能帮忙吗?

code segment     ;inicio de un segmento unico
assume cs:code,ds:code,ss:code
org 100h       ;localidad de inicio del contador
main  proc     ;procedimiento principal

mov ax,cs
mov ds,ax   ; INICIO 

mov ax, x

mov ah,4ch ;comienzo del fin de programa
int 21h    ;fin del programa

main endp

x dw 0A92FH

code ends   ; fin del segmento de codigo
end main    ;fin del ensamble

非常感谢

【问题讨论】:

  • 您的意思是将 X 显示为十进制值吗?您始终可以对十六进制值进行操作,它应该可以正常工作。
  • 是的,但是,我知道我必须有另一个变量,它总是将每个值相加乘以 16 A92F -> (A * 16 ^ 3) + (9 * 16 ^ 2) + (2 * 16 ^ 1) + (F * 16 ^ 0)
  • 误导性标题:这不是 ASCII 十六进制 -> 整数。它让汇编器将源中的十六进制常量转换为二进制整数。

标签: assembly tasm


【解决方案1】:

将数字转换为可打印格式时,通常最容易从最后一位开始。

考虑将 123 转换为“123”,我们如何获得最后一位?这是除以 10(底数)时的余数。所以 123 % 10 给了我们 3 并且 123 / 10 = 12 方便地给了我们在下一次迭代中使用的正确数字。在 x86 上,“DIV”指令可以很好地为我们提供商和余数(分别在 axdx 中)。剩下的就是在字符串中存储可打印的字符。

将所有这些放在一起,您最终会得到如下内容(使用 nasm 语法):

; ConvertNumber
;   Input:
;     ax = Number to be converted
;     bx = Base
;   
;   Output:
;     si = Start of NUL-terminated buffer
;          containing the converted number
;          in ASCII represention.

ConvertNumber:
    push ax            ; Save modified registers
    push bx
    push dx
    mov si, bufferend  ; Start at the end
.convert:
    xor dx, dx         ; Clear dx for division
    div bx             ; Divide by base
    add dl, '0'        ; Convert to printable char
    cmp dl, '9'        ; Hex digit?
    jbe .store         ; No. Store it
    add dl, 'A'-'0'-10 ; Adjust hex digit
.store:
    dec si             ; Move back one position
    mov [si], dl       ; Store converted digit
    and ax, ax         ; Division result 0?
    jnz .convert       ; No. Still digits to convert
    pop dx             ; Restore modified registers
    pop bx
    pop ax
    ret

这需要一个工作缓冲区(在 base = 2 的情况下需要 16 个,并且 NUL 终止符需要一个额外的字节):

buffer: times 16 db 0
bufferend:
    db 0

添加对有符号数字的支持留给读者作为练习。 Here 与适用于 64 位汇编的例程大致相同。

【讨论】:

猜你喜欢
  • 2014-01-30
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
相关资源
最近更新 更多