如何在汇编语言8086中将字符串转换为数字?

时间:2014-12-30 09:53:47

标签: assembly x86

我是汇编的初学者,我需要这个转换的帮助。下面的代码应该从键盘读取的字符串转换为中断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 

2 个答案:

答案 0 :(得分:1)

mul ten   ;ax will store the old result multiplied by 10  

从评论我明白是一个包含值10的字大小的变量。
这意味着乘法是字大小的,因此会覆盖DX 解决方案:将DX更改为p.e. 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 

答案 1 :(得分:0)

mul有两种版本:

  • 乘以两个8位值(ALmul的操作数);将16位结果存储在AX
  • 乘以两个16位值(AXmul的操作数);将32位结果存储在DX AX

你的问题有点模糊,但我认为你想要第一种味道,但你却发现自己面临第二种情况。

要告诉你想要的第一个风味,请给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 不久之后被覆盖了。)

add

修改
我刚刚意识到这会限制可输入的数字范围为0 ... 255,这可能是你想要的。请改用user3628942的解决方案;它允许您输入最多65535的数字。

通常,还有其他方法。以下是使用mul代替mul的解决方案。许多年前,这是处理器架构的一种流行技巧,其中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 要么是昂贵的(即慢速)指令,要么完全不存在。适用于最大65535的数字;为了更高的数字,默默地将其包装为零。

{{1}}