【问题标题】:Reading integers > 9 in x86 assembly在 x86 程序集中读取大于 9 的整数
【发布时间】:2017-12-28 13:43:13
【问题描述】:

我想从x86 程序集中的输入中读取integers,但是当integer 大于9 时会出现一些问题。

我尝试了以下代码(在互联网上找到):

.code
  mov bh,0
  mov bl,10
inputloop:
  mov ah,1
  int 21h
  cmp al,13
jne convertion
jmp startcalc

convertion:
  sub al,48
  mov cl,al
  mov al,bh
  mul bl
  add al,cl
  mov bh,al
jmp inputloop    

startcalc:

我希望我的程序在startcalc 标签开头的ax 寄存器中存储正确的数字。

在这个程序中我应该做什么以及我应该改变什么?

【问题讨论】:

  • 代码看起来在 ax(lo) 中存储了正确的数量,但在 ax(hi) 中还有一个额外的 1
  • 为什么会这样?你认为可能是因为你做了mov ah,1
  • 我应该怎么做而不是 mov ah,1?
  • 没办法,因为中断需要它。您只需要保存/恢复ax 或使用不同的寄存器。实际上不确定您期望的结果。
  • 在 startcalc 标签的开头我希望将输入保存在 ax 寄存器中......一切都是正确的,但例如当我输入 132 时,我正确地有 0D,但我有 01 ...我应该改为 00

标签: assembly x86 dos real-mode


【解决方案1】:

哦!我的!该代码将您的输入限制为 1 个字节内的数字,因此介于 0 和 255 之间。

使用bx 来存储结果,我会使用这样的东西:

  mov bx, 0

inputloop:

  mov ah, 1   ; getc()
  int 21h

  cmp al, 13  ; enter?
  je startcalc

  sub al, 48  ; character to number (assuming user only types '0' to '9')
  mov ah, 0   ; clear ah

  sll bx, 1   ; x2
  mov cx, bx
  sll bx, 2   ; x4 (so x8 total)
  add bx, cx  ; x2 + x8 = x10
  add bx, ax

  jmp inputloop

startcalc:
   mov ax, bx  ; if you want the result in ax instead

现在你的号码至少在 0 到 65535 之间。

【讨论】:

    【解决方案2】:

    你为什么在AX得到错误答案?

    只要用户按回车键,您就会停止聚合整数的过程。所以当用户按下回车键时,存储在AX 中的聚合整数将被010D 替换。 01 因为它的 INT 21h 服务用于从键盘获取整数(这会将 AH 的内容替换为 01)。而0D,因为它是输入键的十六进制值(它将把AL的内容替换为0D)。所以AX寄存器的值不再存储结果(聚合整数)。

    如何解决?

    我希望我的程序在 startcalc 标签开头的 ax 寄存器中存储正确的数字。

    只需在 startcalc 标签的开头添加这些代码行,如下所示:

    startcalc:
    
         mov ah, 0     ; Get rid of 01 in AH
         mov bl, 0     ; Get rid of 0A in BL 
         mov al, bh    ; Store the result in AL
    

    现在您可以访问存储正确结果的AX

    正如Jester 所说,如果你想要更大的数字,你将不得不使用 16 位寄存器,这可以通过以下方式完成:

    16位数字代码:

    要让您的程序接受 16 位数字,请执行以下操作:

    替换这个:

    mov bh,0
    mov bl,10
    

    通过这个:

    mov bx, 0    
    mov di,10    ; DI is a 16bit register that will store our divisor 
    

    还有这个:-

    sub al,48
    mov cl,al
    mov al,bh
    mul bl
    add al,cl
    mov bh,al
    

    通过这个:-

    sub al, 48
    mov ah, 0
    mov cx,ax       ; using 16bit version of CX and AX (store AX into CX)
    mov ax,bx       ; store the previous value of BX into AX  
    mul di          ; multiple the AX with DI  
    add ax,cx       ; add the current integer (CX) with the multiplication result 
    mov bx,ax       ; store AX into BX 
    

    最后是这个:-

    startcalc:
    
         mov ah, 0
         mov bl, 0
         mov al, bh
    

    通过这个:-

    startcalc: 
    
         mov ax, bx
    

    希望对您有所帮助。 :)

    【讨论】:

      猜你喜欢
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多