[英]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.