将数字转换为ASCII以在nasm中打印

时间:2019-11-18 18:39:12

标签: assembly x86 nasm

我做了一个nasm代码,应该打印一个数字,但是当我启动它时,它只会输出4。 代码有什么问题?

代码应遍历数字中的每个数字,同时将当前数字除以10。 其余部分(存储在edx中)是数字的最后一位。

要将一位数字转换为ascii,我只需将数字加48。

section .data
  number dw 255 ;number to print

section .text
  global _start

_start:
  mov eax, [number]
  call convert

convert:
  mov ecx, 10
  idiv ecx         ;divide number by 10
  push eax         ;push result on stack

  mov eax, 0x04    ;output the remainder
  mov ebx, 0x01    ;
  mov ecx, edx     ;move remainder of division in ecx
  add ecx, 48      ;add 48 to the remainder to convert it to ascii
  mov [number], ecx;move remainder to memory
  mov ecx, number  ;pointer of remainder to ecx
  mov edx, 0x01
  int 0x80

  pop eax          ;pop the result again

  cmp eax, 0       ;check if eax == 0
  jne convert      ;if not: go back to convert

mov eax, 0x01 ; exit
mov ebx, 0x00
int 0x80

1 个答案:

答案 0 :(得分:0)

您忘记将eax扩展为edx:eax并将其置零。因此,edx(此处为1)中的任何内容都用于除数的高32位,从而引起您所观察到的问题。

cdq之前添加idiv来解决此问题。该符号将eax扩展为edx:eax。您还需要修复输出逻辑以按相反的顺序打印数字,但是我认为这超出了这个问题的范围。

您犯的另一个错误是仅为number保留2个字节,然后使用mov eax, [number]从中读取4个字节。保留4个字节或使用符号扩展或零扩展的移动:

movzx eax, word [number]  ; either zero-extend
movsx eax, word [number]  ; or     sign-extend

对输入和临时存储使用单独的缓冲区也是一个好主意。