;---------------------------------------------------------
;输入二进制数,转为十六进制后输出
;---------------------------------------------------------
.model small
.data
MAX_BIN db 100 ;二进制长度限制
REAL_LEN db ? ;实际的输入
BIN_DATA db 100 dup(?) ;存储输入的01
RADIX_DATA db 1,2,4,8 ;2^x(x=0,1,2,3)
MSG_PROM db 'Please input binary code :','$'
MSG_ERR db 'Input error,you must enter 0 or 1 !',13,10,'$'
MSG_RLT db 'The binary code to hex is:','$'
BIN_TO_HEX db 100 dup(?)
.code
;---------------------------------------------------------
;屏幕输出以 '$' 结尾的字符串,OPR为字符串变量
;---------------------------------------------------------
macPutTxt macro OPR
mov dx,offset OPR
mov ah,09h
int 21h
endm
;---------------------------------------------------------
;屏幕打印回车换行符,用到寄存器
;---------------------------------------------------------
macPutEnt macro
mov dl,0dh
mov ah,02h
int 21h
mov dl,0ah
mov ah,02h
int 21h
endm
;---------------------------------------------------------
;子过程,测试输入的数据是否是二进制
;如果不是则置 ax 为1,否则置为2
;---------------------------------------------------------
subTestData proc far
push bx
push cx
mov ax,2
mov bx,0
nextTest: mov cl,byte ptr BIN_DATA[bx]
cmp cl,0dh ;回车
jz exitTest
inc bx
cmp cl,30h ;是否是 0
jz nextTest
cmp cl,31h ;是否是 1
jz nextTest
mov ax,1
exitTest: pop cx
pop bx
ret
subTestData endp
;---------------------------------------------------------
;子过程,二进制转十六进制,结果存于BIN_TO_HEX
;---------------------------------------------------------
subBinToHex proc far
irp reg,<ax,bx,si,di> ;保存寄存器
push reg
endm
mov ax,'$'
push ax ;设置哨兵 '$'
mov al,REAL_LEN
mov si,ax
mov ax,0
mov di,-1
next: dec si
mov bh,byte ptr BIN_DATA[si]
inc di
cmp si,0
jz hexone
cmp di,3
jz hexone
cmp bh,30h
jz next ;该位为 0
add al,byte ptr RADIX_DATA[di]
jmp next
hexone: cmp bh,30h
jz pushhex
add al,byte ptr RADIX_DATA[di]
pushhex: cmp al,10
jb digit
add al,55 ;55 = 'A'-10
jmp pushok
digit: add al,30h ;30h = '0'
pushok: push ax
cmp si,0
jz resetsi
mov di,-1
mov al,0
jmp next
resetsi: mov si,0
pophex: pop ax
mov byte ptr BIN_TO_HEX[si],al
inc si
cmp ax,'$'
jnz pophex
irp reg,<di,si,bx,ax> ;恢复寄存器
pop reg
endm
ret
subBinToHex endp
;---------------------------------------------------------
;主过程
;---------------------------------------------------------
main proc far
mov ax,@data
mov ds,ax
macPutTxt MSG_PROM
lea dx,MAX_BIN
mov ax,0c0ah ;先清空键盘缓冲区,然后键盘输入字符串
int 21h
macPutEnt ;打印回车
call subTestData
cmp ax,1
jz error
call subBinToHex
macPutTxt MSG_RLT
macPutTxt BIN_TO_HEX
jmp exit
error: macPutTxt MSG_ERR
exit: mov ah,4ch
int 21h
main endp
end main
评论