簡體   English   中英

如何用匯編語言8086將字符串轉換為數字?

[英]How to convert a string to number in assembly language 8086?

我是匯編的新手,我需要轉換的幫助。下面的代碼應該從帶有中斷01h的鍵盤讀取的字符串中轉換。我知道這是錯誤的,但是您可以幫助我確定錯誤嗎?

mov dx,0 
convert:
    sub al,48 ;to covert to int
    mov bl,al ;in bl will be the digit read 
    mov ax,dx
    mul ten   ;ax will store the old result multiplied by 10
    mov bh,0
    add ax,bx
    mov dx,ax 
mul ten   ;ax will store the old result multiplied by 10  

從注釋中,我知道是一個單詞大小的變量,包含值10。
這意味着乘法是字大小的,因此將覆蓋DX。
解決方案:將DX更改為pe CX

mov cx,0 
convert:
sub al,48 ;to covert to int
mov bl,al ;in bl will be the digit read 
mov ax,cx
mul ten   ;ax will store the old result multiplied by 10
mov bh,0
add ax,bx
mov cx,ax 

mul有2種口味:

  • 將兩個8位值相乘( ALmul的操作數); 將16位結果存儲在AX
  • 將兩個16位值相乘( AXmul的操作數); 將32位結果存儲在DX AX

您的問題有點含糊,但是我想要第一種口味,但是相反,您卻發現自己要面對第二種口味。

為了告訴assember您想要第一種口味,請為mul提供明確無誤的 8位操作數。 在所有匯編器上肯定有效的一種方式是使用8位寄存器,例如BH (我之所以選擇一個寄存器,是因為它的值在mul時顯然是無關緊要的,因為它很快就會被覆蓋)。

sub al,48   ; to covert to int
mov bl,al   ; in bl will be the digit read 
mov ax,dx

mov bh,10   ; use BH to hold factor 10
mul bh      ; multiply AL by BH; the product is stored in AX; DX is unaffected

mov bh,0
add ax,bx
mov dx,ax 

編輯:
我剛剛意識到這將可以輸入的數字范圍限制為0 ... 255,這可能不是您想要的。 改用user3628942的解決方案; 它允許您輸入最大65535的數字。

通常,還有其他方法。 以下是使用add而不是mul的解決方案。 許多年前,這是處理器架構的流行技巧,而mul要么是昂貴的(即,緩慢的)指令,要么根本不存在。 適用於最大65535的數字; 靜默換成零以獲得更高的數字。

sub al,48    ; ASCII value --> numeric value
mov ah,0     ; AX = numeric value of digit
add dx,dx    ; DX = 2 * original DX
add ax,dx    ; AX = 2 * original DX + digit
add dx,dx    ; DX = 4 * original DX
add dx,dx    ; DX = 8 * original DX
add dx,ax    ; DX = 10 * original DX + digit

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM