; *********************************************************************
;  Module: BINTOASC.ASM
;  Author: Scott Teresi, www.teresi.us
;  Created: October 25, 1995   Modified: October 31, 1995
;  Description: This module contains a procedure to convert a value
;	stored in register AX into a number depending on radix
;	specified in BX and then display the number on the screen.
; *********************************************************************

;	Procedures available in this module:

	PUBLIC BINARY_TO_ASCII


CODESEG SEGMENT PARA PUBLIC 'CODE'


BINARY_TO_ASCII PROC FAR

; Note: this procedure was adapted from Dr. Estell's MODULES.ASM code.
;
; Converts a binary number in AX register using radix value given in BX
; into ASCII characters and outputs them one by one on the screen.
; On entry: AX = binary number to be output
;	    BX = radix for result, must be between 2 and 16
;	    SI = address at which number will be stored as string to output
; On exit:  nothing

	PUSH AX
	PUSH BX 	    ; save registers
	PUSH CX
	PUSH DX
	PUSH DI

	MOV DI, 0	    ; assume number positive; set DI as flag
	CMP AX, 7FFFH	    ; see if number is negative
	JBE HAVE_MAGNITUDE  ; bypass magnitude operation if number is positive
	NEG AX		    ; get magnitude of 2's complement value
	MOV DI, 1	    ; set DI flag to indicate number was originally -

HAVE_MAGNITUDE:
	MOV DX, 0	    ; clear DX to be ready to store characters
	MOV CX, 0	    ; zero counter
	MOV BH, 0	    ; set divisor (already in BL)

DO_NUM:
	DIV BX		    ; divide number (DX:AX) by radix (BX)
	ADD DL, '0'	    ; convert remainder to ASCII digit character
	CMP DL, '9'	    ; was the digit greater than nine?
	JBE PUSH_CHAR	    ; if not then bypass
	ADD DL, 'A'-'9'-1   ; else shift it up into hex character range

PUSH_CHAR:
	PUSH DX 	    ; store character on stack
	MOV DX, 0	    ; reset upper word of dividend to zero
	INC CX		    ; increment digit counter
	CMP AX, 0	    ; is quotient equal to zero?
	JNE DO_NUM	    ; if not, then continue the conversion

	CMP DI, 0	    ; see what sign DI flag indicates
	JE MAKE_STRING	    ; bypass the printing of a sign if SI = 0
	MOV AH, 2	    ; specify DOS service to print a character
	MOV DL, '-'	    ; print out a negative sign
	INT 21H 	    ; call DOS service

MAKE_STRING:
	MOV BX, 0

STORE_NUMBERS:
	POP AX		    ; pop the stored ASCII numbers (characters)
	MOV [SI][BX], AL    ; store characters into memory, offset from SI
	INC BX
	LOOP STORE_NUMBERS  ; loop until all characters are off the stack
	MOV AL, 0
	MOV [SI][BX], AL    ; terminating character for string

	POP DI
	POP DX		    ; restore the registers
	POP CX
	POP BX
	POP AX

	RET

BINARY_TO_ASCII ENDP

CODESEG ENDS
	END

