Joseph Fontenelle
Joseph Fontenelle

Reputation: 13

Mips SLL operator

I am trying to implement 2^15 and decrement by 1 with lls. I am basically trying to do 2^15,2^14,etc. and then print that value. However, i am having trouble and I can't figure out why. It stops after two iterations because it goes to 0. the output is (32768 16384 0 -16384 -32768 -49152 -65536 -81920 etc) Any suggestions? Thank you

   addi $s1, $zero, 2

Loop2:
beqz $s1, end2 #if 15 reches 0 than end
sll $t1, $s1, 14
#decrement by 1
addi $s1,$s1,-1


#add 1 into $v0 print
addi $v0, $zero, 1

#move ($s0) into $a0
move $a0, $t1

syscall

Upvotes: 0

Views: 303

Answers (2)

LeoYulinLi
LeoYulinLi

Reputation: 129

sll $t1, $s1, 2 in this case means $t1 = $s1 << 2, which is just multiplying $s1 by 4. To do ^15 you probably want to do

addi $s1, $zero, 2
sll $t1, $s1, 14

For the edited question

This is my solution to it:

addi $s1, $zero, 2  # base is 2
sll $t1, $s1, 14    # $t1 = 2 << 14

Loop2:
addi $v0, $zero, 1  # use print int service
move $a0, $t1       # load $t1 into argument
syscall

srl $t1, $t1, 1     # shift right, effectively decrement the exp by 1

bnez $t1, Loop2     # loop until $t1 is zero

Here is a few major things I changed:

  • moved beqz $s1, end2 #if 15 reches 0 than end to the end of the loop and flipped the logic.
    • the idea is you want to go back up unless the result becomes 0. Not sure if the end2 is another label or just a typo, but you want to have something branch back to the beginning of the loop.
  • addi $s1,$s1,-1 is actually changing the base, not the exponent.
    • so what you had was basically 2 << 14, 1 << 14, 0 << 14, -1 << 14, etc.
    • to decrease the exponent in this case, all you have to do is unshift (or shift right) the previous result by 1. Hence the srl $t1, $t1, 1 in my code.

Upvotes: -1

Erik Eidt
Erik Eidt

Reputation: 26646

I think you are looking for a shift by a variable amount, so use sllv.

Try something like this, which is assembly code for 1 << n:

li $t0, 1
sllv $t1, $t0, $s1

in place of your shift (sll $t1, $s1, 2).

Upvotes: 3

Related Questions