将双字数字打印到字符串

时间:2010-03-11 20:27:29

标签: assembly dos tasm

我在si:bx中有双字数字。 如何将其作为字符串写入数组?

1 个答案:

答案 0 :(得分:2)

最简单的方法是将数字转换为十六进制。每组4位变为十六进制数字。

; this is pseudocode
mov di, [addr_of_buffer]  ; use the string instructions
cld                       ; always remember to clear the direction flag

; convert bx
mov cx, 4    ; 4 hexits per 16 bit register
hexLoopTop:
mov al, bl   ; load the low 8 bits of bx
and al, 0x0F ; clear the upper 4 bits of al
cmp al, 10
jl decimal
add al, 65   ; ASCII A character
jmp doneHexit:
decimal:
add al, 48   ; ASCII 0 character
doneHexit:
stosb        ; write al to [di] then increment di (since d flag is clear)
ror bx       ; rotate bits of bx down, happens 4 times so bx is restored
loop hexLoopTop

; repeat for si, note that there is no need to reinit di

现在,如果你想要十进制输出,你需要一个更复杂的算法。显而易见的方法是重复划分。请注意,如果您有32位CPU(386或更高版本),则可以使用16位模式下的32位寄存器,这样可以更轻松。

将si:bx移动到eax中开始。要获得下一个数字,执行cdq指令将eax扩展到edx:eax,div为10,edx中的余数为下一个数字。 eax中的商是0,在这种情况下你已经完成,或者是下一轮循环的输入。这将首先为您提供最重要的数字,因此您需要在完成后反转数字。你的缓冲区至少应该是2 ^ 32舍入的基数为10的对数,即10。调整此算法以使用有符号整数并不太难。