繁体   English   中英

程序集 8086。从标准输入中读取几个基数为 2 的数字。在屏幕上打印这些基数为 10 的数字

[英]Assembly 8086. Read from the standard input several numbers, in base 2. Print on the screen these numbers in base 10

所以,我必须将以 2 为底数的数字转换为以 10 为底数的数字,我不知道该怎么做。这就是我的程序现在的样子,但我不确定我现在得到的是否正常工作。 转换部分真的让我很为难,但我的代码中肯定有很多错误,所以任何帮助将不胜感激。

   assume cs:code, ds:data

data segment
msg db 'Give numbers:$'
numbers LABEL BYTE
    max_size DB 100
    numbers_len DB ?
    number DB 100 dup (?)
ten db 10
errm db 'Numbers not in binary.$'
data ends
code segment
start:

mov ax,data
mov ds,ax

mov ah,09h
mov dx,offset msg
int 21h

mov AH,0Ah
mov DX,offset numbers
int 21h

mov CL,numbers_len
mov CH,0
mov SI,0    
repeat:
    mov AL,number[SI]
    cmp AL,' '
    je conversion

    check:
    cmp AL,'0'
    jb erro
    cmp AL,'1'
    ja erro

    jmp conversion
    continue:
    inc SI
    dec cx
    jcxz print 
    jmp repeat


conversion:

    jmp continue

print:
    pop dx
    add dl,'0'
    mov ah,02h
    int 21h
    loop print  
erro:
    mov ah,09h
    mov dx,offset errm
    int 21h

mov ax,4c00h
int 21h

code ends
end start

首先,无法直接执行 base-2 到 base-10 的转换:您必须将 base-2 表示形式转换为寄存器中的实际值,然后将其转换为 base-10。 这是因为这些基数彼此不相关,例如,无法通过对 2 进行整数次幂来获得 10。

下面是从 base-2 字符串到数字的转换代码。 不执行错误检查,每个不是1的字符都被简单地视为0

; input : bx - the starting address of the string, cx - its length
; output : ax - contents of the string interpreted as base-2
from_bin:
  mov di, bx
  add di, cx
  sub di, 1
  xor ax, ax
  mov dx, 1

.loop:
  cmp di, bx
  jb .end

  cmp byte [di], '1'
  jne .loop_next

  add ax, dx

.loop_next:
  shl dx, 1
  sub di, 1
  jmp .loop

.end:
  ret

如您所见,如果当前位置为1 ,则代码通过向其中添加dx来构建ax中的返回值。 dx对应于循环每次迭代中 2^n 的值,其中n是字符串中的当前位置,从零开始。

将值转换为 base-10 的代码使用除法将存储在寄存器中的“本机”base-2 值转换为该值的连续 base-10 数字。

; input : ax - the number to convert
; di - the last writable address of the output buffer
; output : di - the address of the last written character
; destroys bx, cx, dx
to_dec:
  mov cx, 10

.loop:
  xor dx, dx
  div cx

  mov bx, dx
  or bl, '0'
  mov [di], bl
  test ax, ax
  jz .end

  sub di, 1
  jmp to_dec

.end:
  ret

转换是“向后”完成的:它从最低位置开始,只要除法的结果不为零,它就一直向上工作——这意味着还有更多要转换。 这也是为什么函数需要获取缓冲区的最后一个可写地址而不是其开头的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM