## LSU EE 4720 Computer Architecture Spring 2014
#
#  Classroom example for review of MIPS:  Convert int to hex string.
#  This is the final cleaned-up, commented version.

        .text

###############################################################################
#
# Unsigned Integer to Hexadecimal String
#

itos:
        ## Register Usage
        #
        # CALL VALUES:
        #  $a0: Unsigned integer to convert.
        #  $a1: Address of storage.
        #       Initialized to null-terminated string of blanks.
        #  $a2: Length of storage.
        #
        # RETURN:
        #       There is no return register value ..
        #       .. instead write storage at $a1 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

        add $t3, $a1, $a2   # Compute address of end of string.

LOOP:
        andi $t0, $a0, 0xf  # Extract digit from call value.
        srl $a0, $a0, 4     # Shift call value to next position (for later).
        slti $t2, $t0, 10   # Check whether hex digit is 0-9.
        bne $t2, $0 SKIP    # If digit is 0-9 skip ahead.
        addi $t1, $t0, 48   # Compute ASCII value assuming 0-9.
        addi $t1, $t1, 39   # Add extra amount if digit is a-f.
SKIP:
        sb $t1, 0($t3)      # Store ASCII value of digit into memory.
        bne $a0, $0, LOOP   # And continue if call value is non-zero.
        addi $t3, $t3, -1

DONE:
        jr $ra
        nop


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

        .data
msg:
        .asciiz "The value of %/s4/5d = 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


        .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