在x86汇编中读取整数> 9

问题描述 投票:0回答:2

我想从integers汇编中的输入读取x86,但是当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:

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

我应该怎么做以及我应该在这个计划中改变什么?

assembly x86 dos real-mode
2个回答
0
投票

哦!我的!该代码将输入限制在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之间。


1
投票

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

只要用户按Enter键,就会停止聚合整数的过程。因此,当用户点击enter键时,存储在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

希望有所帮助。 :)

© www.soinside.com 2019 - 2024. All rights reserved.