汇编中的字符串到整数

String to integer in assembly

我想将字符串转为整数 例如,当我在字符串中输入 1234 时,它会转换为整数 1234。 但是,当我输入1234时,结果只有12个,我不知道是什么问题。

%include "asm_io.inc"

segment .bss
string  resb    32


segment .text
global  main

main:

  enter 0,0     ; setup stack frame
  pusha

  mov   edx, 0
  mov   ecx, 0
  mov   ebx, 0

repeat: call    read_char

  sub   eax, 48
  mov   esi, eax
  mov   eax, ecx
  mov   ebx, 10
  mul   ebx
  mov   ecx, eax
  add   ecx, esi
  mov   byte [string+edx], al

  cmp   al, 0x0a
  jne   repeat
  mov   byte [string+edx-1], 0

  mov   eax, ecx
  call  print_int
  call  print_nl

  popa
  mov   eax, 0  ; return value
  leave         ; leave stack frame
  ret

只是分析,没有运行,看来你的逻辑是错误的。在第二次循环迭代中,您将 eax 等于 1,因此在将其乘以 10 (ebx) 后,您将产生等于 Enter 的 ascii 值的结果 - 0x0a (10dec).

您应该在读取字符后立即移动检查输入值。所以试着让你的循环像这样

repeat: 
  call  read_char
  cmp   al, 0x0a
  je    exit_loop // exit the loop if enter
  //code as before
  jmp repeat //jump unconditionally to the beginning of the loop
exit_loop:
   mov   byte [string+edx-1], 0

我认为可能还有一些其他问题,因为我看不到 edx 会在哪里递增。

但正如我所写 - 它只是通过分析 w/o 实际上 运行。你有程序和调试器。调试它!按照 Michael Petch 的建议单步执行代码、分析寄存器并确认发生了什么。