在 MIPS 上生成随机数

Generate random number on MIPS

我找到了 this possible solution 但它给了我类似的东西:

598756802  
373297426  
-2011171535   

这就像打印地址而不是数值。如何解决?

我还需要为生成器设置一个范围。比如生成一个0到99之间的随机数。
我该怎么做?
Obs:已经尝试使用系统调用 42 代码,但出现错误。
(OFF:至少说出反对票的原因,我没有 crystal 球)。

代码:

.text
    li $v0, 41          # Service 41, random int    
    syscall            # Generate random int (returns in $a0)
    li $v0, 1          # Service 1, print int
    syscall            # Print previously generated random int  

更新 这总是给我相同的数字,1000

.text
    li $a1, 2501
    li $v0, 42   #random
    add $a0, $a0, 1000
    li $v0, 1
    syscall

我可以使用以下代码使其工作:

.text
    li $a1, 100  #Here you set $a1 to the max bound.
    li $v0, 42  #generates the random number.
    syscall
    #add $a0, $a0, 100  #Here you add the lowest bound
    li $v0, 1   #1 print integer
    syscall

你的最后一个代码块没有调用 RNG 系统调用,只调用了 print 系统调用。

很简单,你只需要做到以下几点

li $v0, 42  # 42 is system call code to generate random int
li $a1, 100 # $a1 is where you set the upper bound
syscall     # your generated number will be at $a0

li $v0, 1   # 1 is the system call code to show an int number
syscall     # as I said your generated number is at $a0, so it will be printed

如果您想将生成的数字存储在数组中,这是一种方法:

move $s2, $s0      # copy the initial pointer to save array

li $v0, 42            # system call to generate random int
la $a1, 100       # where you set the upper bound
syscall              # your generated number will be in $a0

sb $a0, 0($s2)     # put the generated number at the position pointed by $s2

addi $s2, $s2, 1       # increment by one the array pointer

因为我们只想要 0-100 的范围,所以我们可以将每个数字存储在一个字节中,而不是使用 sw 并将指针递增 4。

生成随机数所需要做的就是更改上限,您将在寄存器 $s1 中获得它。以下代码将生成范围为 0..3

的随机数
addi $v0, $zero, 30        # Syscall 30: System Time syscall
syscall                  # $a0 will contain the 32 LS bits of the system time
add $t0, $zero, $a0     # Save $a0 value in $t0 

addi $v0, $zero, 40        # Syscall 40: Random seed
add $a0, $zero, $zero   # Set RNG ID to 0
add $a1, $zero, $t0     # Set Random seed to
syscall

addi $v0, $zero, 42        # Syscall 42: Random int range
add $a0, $zero, $zero   # Set RNG ID to 0
addi $a1, $zero, 4     # Set upper bound to 4 (exclusive)
syscall                  # Generate a random number and put it in $a0
add $s1, $zero, $a0     # Copy the random number to $s1