Search code examples
assemblymipsbyte-shifting

MIPS - Shifting register values by a numeric value


Can someone explain this to me? The problem is:

sll $t2, $t0, 44

and the goal is to find the value of $t2 after the operation. The initial values are:

$t2 = 0x12345678
$t0 = 0xAAAAAAAA

I understand that the pseudocode translation of "sll $t2, $t0, 44" is:

t2 = t0 << 44

and that the binary representation of t0 and t2 are:

t2 = 10010001101000101011001111000
t0 = 10101010101010101010101010101010

But how do you shift by 44 bits? I thought that there are only 32 bits for one value to begin with. How do I find the value of $t2 by shifting $t0 by 44 bits?


Solution

  • Sometimes it is necessary to perform a shift by a ‘variable’ amount supplied through a third register: sllv $s1,$s2,$s3 #s1 = s2 << s3 Implement the new sllv instruction using real MIPS instructions.

    Note: shift amount must be between 0 and 31 (inclusive). So value in $s3 must be reduced modulo 32. This is easily done by ‘anding’ with 000…0011111 = 0x1F. This operation handles both cases when $s3 is positive or negative.

    sllv $s1,$s2,$s3 # s1 = s2 << s3
    add $s1, $s2, $0 # s1 <- s2
    add $t0, $s3, $0 # t0 <- s3 (s3 must be preserved)
    andi $t0, $t0, 0x1F # take mod 32
    beq $t0, $0, EXIT # if t0 == 0, do nothing
    addi $t1, $0, 0 # set i == 0 (start from 0)
    LOOP:
    sll $s1, $s1, 1
    addi $t1, $t1, 1 # i=i+1
    bne $t1, $t0, LOOP # LOOP while i is still not equal to t0
    EXIT:
    

    Here you go, this is the idea they mean in your text book, for a 32-bit machine, you need to take the modulo 32 of the shift (shifting by 36 can be explained like shifting by 4 if you think of it like a rotate) but what they mean is to take the modulo.