Mips Assembly: Convert from Integer to Hexadecimal

Mips Assembly: Convert from Integer to Hexadecimal

I found this code snippet that I believe converts an integer to hex. However, I'm not following it at all. I added the comments that say what I believe is happening, but I have no idea WHY it's being done. So, assuming I correctly noted what each line was doing, can someone please explain to me why it's being done? As in how it in any way helps convert to hex?

$a0 is the integer value

$a1 is the address of where the result should be

        addi $t0, $0, 48       #set $t0 equal to 48 
        sb $t0, 0($a1)         #store $to (48) at location 0 in $a1
        addi $t0, $0, 120      #set $t0 equal to 120
        sb $t0, 1($a1)         #store $t0 (120) at location 1 in $a1
        addi $t1, $a1, 9       #set $t1 = the address + 9

LOOP:

        andi $t0, $a0, 0xf    #$t0 = 1 if $a0 and 0xf are the same (0xf = beginning of hex)?

        slti $t2, $t0, 10     #if $t0 is less than 10, $t2 = 1, else 0
        bne $t2, $0,  DIGIT   #if $t2 does not equal 0, branch to DIGIT
        addi $t0, $t0, 48     #set $t0 equal to 48
        addi $t0, $t0, 39     #set $t0 equal to 39 (why did we just write over the 48?)
DIGIT:

        sb $t0, 0($t1)        #set $t0 equal to whatever's in location 0 of $t1

        srl $a0, $a0, 4       #shift right 4 bits

        bne $a0, $0, LOOP     #if $a0 does not equal 0, branch to LOOP
        addi $t1, $t1, -1     #set $t1 = $t1 - 1

DONE:

        jr $ra                #set the jump register back to $ra
        nop
1

1 Answer

    slti $t2, $t0, 10     #if $t0 is less than 10, $t2 = 1, else 0
    bne $t2, $0,  DIGIT   #if $t2 does not equal 0, branch to DIGIT
    addi $t0, $t0, 48     #set $t0 equal to 48
    addi $t0, $t0, 39     #set $t0 equal to 39 (why did we just write over the 48?)

MIPS uses branch delay slots, meaning that the instruction following the branch instruction always is executed before the branch is taken (or not taken).

So what this says is "If $t0 is less than 10 (i.e. in the range 0..9), goto DIGIT, but first add 48 (ASCII '0') regardless of the value of $t0. In case the branch was taken you'll now have converted from 0..9 to '0'..'9'. In case the branch wasn't taken, $t0 was originally in the range 10..15 and will now be in the range 58..63, so we add 39 more to get a value in the range 97..102 (the ASCII codes for 'a'..'f')".

6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.