1

Here I am writing a function in MIPS assembly where the following function returns a random number within a given range. I know I could syscall 42 to do this but I am trying to learn from scratch. I use syscall 41 to get a random integer. The code appears to work in most cases, but sometimes the returned value is out of bounds. I believe this has to do with the leading bit for this stored value. Is the problem when I use rem? Is this command storing a signed value? How should I handle this? Do I write more code to perform two's complement or simply use a different command?

getRandom:
    # $v0 getRandom($a0, $a1)
    # max - min
    # $a1 - $a0
    sub     $t0, $a1, $a0   # max - min
    addi    $t0, $t0, 1 # $t0 = max - min + 1

    addi    $sp, $sp, -16
    sw  $a0, 0($sp) # *($sp + 0) = $a0
    sw  $a1, 4($sp) # *($sp + 4) = $a0
    sw  $t0, 8($sp) # *($sp + 8) = $a0

    li  $v0, 41
    syscall

    # $a0 = rand()

    lw  $t0, 0($sp) # $t0 = min
    lw  $t1, 4($sp) # $t1 = max
    lw  $t2, 8($sp) # $t2 = max - min + 1
    addi    $sp, $sp, 16    #restore ram

    rem $a0, $a0, $t2   # $a0 = a0 % $t2

    add $v0, $a0, $t0    

    jr  $ra

PSIKLO
  • 27
  • 8

1 Answers1

0

rem $a0, $a0, $t2 This line stores a signed value in $a0.

I should use:

remu $a0, $a0, $t2

This would store an unsigned value in $a0.

PSIKLO
  • 27
  • 8