The MAL procedure print_int implements the puti instruction for positive integers. The number to be printed is passed by value in register $4. The procedure is called as follows:
.data
I: .word # number to print
.text
.
.
lw $4, I
jal print_int
The procedure uses the system stack to:
Although not required, it is good practice to save register $4. The MAL I/O instructions, such as putc, overwrite $4 and $2. By saving and restoring $4, the procedure returns $4 unchanged to the calling program.
The procedure uses temporary registers and the system stack to perform all computations and requires no memory allocation in the .data section.
#
# print_int: a procedure to print a positive integer
# return value: none
# parameters: $4, the integer to be printed
# registers: $12, temporary for $4 during conversion
# $11, ascii digits during conversion
# $10, number of ascii digits converted
#
print_int:
# save return address and $4 on stack
sw $ra, ($sp) # save return address
add $sp, -4
sw $4, ($sp) # save $4
add $sp, -4
# initialize temporary registers
li $10, 0 # digit count <- 0
move $12, $4 # $12 <- number to print
# loop to extract least significant digit
loop: rem $11,$12, 10 # $11 <- least sig digit
add $11, '0' # convert digit to ascii
sw $11, ($sp) # store digit on stack
add $sp, -4
add $10, 1 # increment digit count
div $12, 10 # shift right one digit
bgtz $12, loop # repeat until ($12=0)
# loop to print digits stored on stack
print: add $sp, 4
lw $11, ($sp) # load digit from stack
putc $11 # print the digit
sub $10, 1 # decrement digit count
bgtz $10, print # repeat until (count=0)
# restore registers and return
add $sp, 4
lw $4, ($sp) # restore $4 from stack
add $sp, 4
lw $ra, ($sp) # restore $ra from stack
jr $ra # return to calling program