Search code examples
assemblymipsmips32

MIPS srl by a variable


I've done some searching but can't seem to find the answer. Most likely because I'm not really sure how to word it.

if I have the following code

for (i = 0; i < 10; i++) {
    x = y >> i
    ...
}

is there a way to implement the y >> i instruction without a another loop?

I know this doesn't work, but say the value of i was stored in $s1, doing something this

srl $t3, $s5, $s1

as opposed to having to setting $t3 to the value of $s5 and then looping through this statement i times

srl $t3, $t3, 1

Hopefully that makes sense.

Basically I want y * 2^-i each time through the for loop.

Thanks for any help, or even just some beratement about how this is a dup question and I can read that full of shame and get an answer.


Solution

  • The MIPS32™ Architecture For Programmers Volume II: The MIPS32™ Instruction Set lists the following shift instructions:

    • SLL Shift Word Left Logical
    • SLLV Shift Word Left Logical Variable
    • SRA Shift Word Right Arithmetic
    • SRAV Shift Word Right Arithmetic Variable
    • SRL Shift Word Right Logical
    • SRLV Shift Word Right Logical Variable

    The ones of interest to you are the ones with Variable in their names, and they work as follows:

    SLLV rd, rt, rs :  rd ← rt << rs
    SRAV rd, rt, rs :  rd ← rt >> rs (arithmetic)
    SRLV rd, rt, rs :  rd ← rt >> rs (logical)
    

    Only the low-order 5 bits of rs are used, giving you shift amounts in the range 0-31.