Skip to content

Instantly share code, notes, and snippets.

@xavery
Last active January 16, 2016 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xavery/b25598ccee27675200fa to your computer and use it in GitHub Desktop.
Save xavery/b25598ccee27675200fa to your computer and use it in GitHub Desktop.
A DOS program to read binary values and convert them to decimal
bits 16
cpu 8086
org 100h
start:
.readloop:
; read the binary string.
mov ah, 0ah
mov dx, bin_buf
int 21h
; if we read nothing, end the program.
cmp byte [bin_buf + 1], 0
je .end
; issue a crlf to write the output on a new line.
mov dx, crlf
mov ah, 9
int 21h
; convert from binary
mov bx, bin_buf + 2
mov cl, [bin_buf + 1]
mov ch, 0
call from_bin
; to decimal
mov di, dec_buf + 4
call to_dec
; and print.
mov dx, di
mov ah, 9
int 21h
jmp .readloop
.end:
ret
; input : bx - the starting address of the string
; cx - its length
; output : ax - contents of the string interpreted as base-2
; destroys dx, di
from_bin:
mov di, bx
add di, cx
sub di, 1 ; di now contains the ending address of the string
xor ax, ax ; the return value
mov dx, 1 ; current value of the position in base-2
.loop:
; check if we're past the start.
cmp di, bx
jb .end
cmp byte [di], '1'
jne .loop_next
; if we got a 1, add the current value to the return value.
add ax, dx
.loop_next:
shl dx, 1 ; scale the position
sub di, 1 ; move back one character
jmp .loop
.end:
ret
; 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 ; constant divisor
.loop:
xor dx, dx ; div takes dx:ax, we want ax only.
div cx
; convert the 0-9 remainder to ascii and write it to the string.
mov bx, dx
or bl, '0'
mov [di], bl
; if the quotient is zero, we have nothing more to do.
test ax, ax
jz .end
; the nonzero quotient is used as the base in the next iteration : it
; represents the next position in the string.
sub di, 1
jmp to_dec
.end:
ret
; buffer structure for the DOS buffered read call. we want 16 characters at most
; but the buffer needs space for the trailing CR as well.
bin_buf db 17, 0
times 17 db 0
; buffer for the function building the decimal representation.
dec_buf times 5 db 0
crlf db 13, 10, '$'
APPNAME := bin2dec
$(APPNAME).com : $(APPNAME).asm
nasm -f bin -o $(APPNAME).com -l $(APPNAME).lst $(APPNAME).asm
.PHONY : clean
clean :
$(RM) $(APPNAME).com $(APPNAME).lst
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment