Signed 16-bit Binary to ASCII

Ron Kreymborg


The following file shows a demonstration program to convert a 16-bit, signed binary number to an ASCII string. The string will have a leading "-" if the number was signed, and a space otherwise. Leading zeroes are not suppressed. This give a total of 6 characters. Some representations are:

            123456
     784:    00784
   27439:    27439
    -462:   -00462
  -32767:   -32767

Certainly not the most efficient method or the shortest I am sure. However it works and as time is not a problem it will do for now. If program space becomes a problem I will look at the binary->bcd->ascii methods using shifts. If, dear reader, you have any suggestions they would be most welcome.

The program is written in Microchip MPASM assembler and can be included in an MPLAB project. Check the special setup required.

A zipped copy of this file is available: D2A16.ZIP

Please refer all queries to Ron Kreymborg

D2A16.ASM

;****************************************************************
; Signed 16-bit to ASCII converter. Enter with number in hi/lo.
; returns with ASCII equivelent at . The first char will
; be sign: "-" or " ". The latter is easily changed to "+". 
; Leading spaces are not supressed.  Uses program 65 words.

toascii	movlw	ascii		; setup a pointer
	movwf	fsr
	btfss	hi,7		; negative number?
	goto	skpneg		; no

	comf	hi		; negate the number
	comf	lo
	incf	lo
	btfsc	status,z
	incf	hi
	movlw	"-"		; provide a negative sign
	goto	minus

skpneg	movlw	" "		; blank "sign" for positive
minus	movwf	indf		; store sign
	incf	fsr		; fill ascii buffer with ("0"-1)
	movlw	"0"-1
	movwf	indf
	incf	fsr
	movwf	indf
	incf	fsr
	movwf	indf
	incf	fsr
	movwf	indf

	movlw	ascii+1		; do the subtractions
	movwf	fsr
	dodigit	10000
	dodigit	1000
	dodigit	100
	dodigit	10
	movf	lo,w		; ls byte is already correct
	addlw	"0"		; convert to ascii
	movwf	indf
	return			; done

; Subtract the number in shi/slo from hi/lo until the result
; is negative, incrementing the ascii equivelent each time.

dosub	incf	indf		; increment ASCII character
	movf	slo,w		; subtract current power of 10
	subwf	lo,f
	movf	shi,w
	btfss	STATUS,C
	addlw	1
	subwf	hi,f
	btfsc	STATUS,C	; any carry?
	goto	dosub		; no, keep subtracting

	movf	slo,w		; reverse the last subtraction
	addwf	lo,f
	movf	shi,w
	btfsc	STATUS,C
	addlw	1
	addwf	hi,f
	incf	fsr		; step to next ASCII position
	return