## LSU EE 4720 Computer Architecture Spring 2011
#
#  Classroom example for review of MIPS:  Convert int to hex string.

        .data
msg:
        .asciiz "The value of 0x%/s4/x is %/a1/s\n"
str:
        .align 4
        .space 12
values:
        .word 1234
        .word 0x1234
        .word 0xa9
        .word 0x0
        .word 0xf
        .word 0xf00d
        .word -1

###############################################################################
#
 ##  Test Code
#
#  This code calls the hex to string routine multiple times using
#  data appearing above.
#


        .text
        .globl __start
__start:
        la $s2, values
        addi $s3, $0, -1;
MLOOP:
        lw $a0, 0($s2)
        la $a1, str
        lui $t0, 0x2020
        ori $t0, $t0, 0x2020
        sw $t0, 0($a1)
        sw $t0, 4($a1)
        sw $t0, 8($a1)
        sb $0, 11($a1)
        jal itos
        addi $a2, $0, 10
        lw $s4, 0($s2)
        la $a1, str
        la $a0, msg
        addi $v0, $0, 11        
        syscall
        addi $s2, $s2, 4
        bne $s4, $s3 MLOOP
        li $v0, 10
        syscall
        nop


###############################################################################
#
# Int to Hex String
#

itos:
        ## Register Usage
        #
        # $a0: CALL VALUE: Integer to convert
        # $a1: Address of storage. 
        #      Initialized as null-terminated string of blanks.
        # $a2: Length of storage.
        #
        # RETURN:
        #      Write storage with hex representation of $a0.
        #
        # NOTE: Registers $a0-$a4 and $t0-$t7 can be modified.
        # NOTE: 'a' = 97, 'z' = 122,  'a' - 'A' = 32
        # NOTE: '0' = 48 = 0x30


        addi $t0, $0, 48
        sb $t0, 0($a1)
        addi $t0, $0, 120
        sb $t0, 1($a1)
        addi $t1, $a1, 9

LOOP:
        andi $t0, $a0, 0xf

        slti $t2, $t0, 10
        bne $t2, $0,  DIGIT
        addi $t0, $t0, 48
        addi $t0, $t0, 39
DIGIT:
        sb $t0, 0($t1)

        srl $a0, $a0, 4

        bne $a0, $0, LOOP
        addi $t1, $t1, -1

DONE:
        jr $ra
        nop