CSC231 Printing Bytes in Decimal

From dftwiki3
Jump to: navigation, search

--D. Thiebaut (talk) 10:46, 11 October 2017 (EDT)



Source

;;; printByteDec.asm
;;; D. Thiebaut
;;;
;;; Takes the byte stored in n and prints it in decimal
;;; on the screen.
;;; For example, if n is set to 231, the output of the program is
;;;
;;; n = 231
;;; 
	section .data
n	db	231		;the number to print in decimal
msg	db      "n = "	        ;a message used to prefix the output
d1	db	' '		;the 3 digits composing n (some might
d2	db	' '		;end up being 0)
d3	db	' '
lf	db	10		;a line feed to terminate the printout
	
	global	_start
	section .text
	
_start:	mov	eax, 0		;use dwords for division
	mov	edx, 0		;setup edx:eax <-- 0
	
	mov	al,  byte[n]	;edx:eax <-- n
	mov	ebx, 10		;get ready to divide by 10
	div	ebx		;edx <- d3 in binary
				;eax <- quotient (d1d2)
	add	dl, '0'		;binary to ascii
	mov	byte[d3], dl    ;d3 now contains ascii of
				;least significant digit of n 

	mov	edx, 0		;reset edx to 0
	div	ebx		;edx <- d2 in binary
				;eax <- quotient (d1)
	add	dl, '0'		;binary to ascii 
	mov	byte[d2], dl	;d2 now contains middle digit
	add	al, '0'		;binary to ascii
	mov	byte[d1], al	;d1 now contains most sig. digit

	mov	eax, 4		;print "msg = d1d2d3" followed by
	mov	ebx, 1		;line-feed
	mov	ecx, msg
	mov	edx, 4+4
	int	0x80

;;; exit
	mov     eax,1
	mov     ebx,0
	int     0x80	; final system call


Output


cs231a@aurora ~/handout $ nasm -f elf printByteDec.asm  

cs231a@aurora ~/handout $ ld -melf_i386 printByteDec.o -o printByteDec

cs231a@aurora ~/handout $ ./printByteDec 
n = 231

cs231a@aurora ~/handout $