0

I am currently looking for the best method for performing an n power2 function. In short, the code in MIPS should calculate 2n. n being a positive number stored in $a0. However, as of right now my results are coming one power less.

My Attempt

main:

    # initialize 
    la  $a0,3       #n counter
    li  $s0,2       #base number
    li  $s1,0       #calculated value

While:  
    beq $a0,$zero,exit      #Checks if n is zero, if yes exit program 
    sllv $s1,$s0,$a0        #Shift left logical by n, this should do the math 2^n

exit:

Results from QtSpim

Konrad Lindenbach
  • 4,911
  • 1
  • 26
  • 28
Ace NA
  • 121
  • 1
  • 2
  • 8
  • Related: [Multiplication by a power of 2 using Logical shifts in MIPS assembly](https://stackoverflow.com/q/18812319) – Peter Cordes Mar 25 '22 at 01:24

1 Answers1

4

"Failed" isn't a very informative statement. Anyway, the correct syntax for beg $a0,$zero,j Exit is beq $a0, $zero, exit but you don't even need that check. You should load $s0 with 1 not 0 since 2^0 is 1 and sll $s0, 2, $a0 should be sllv $s0, $s0, $a0.

Jester
  • 56,577
  • 4
  • 81
  • 125
  • Fixed the issues and j exit code. It is now running in QtSpim but sadly the results are not being pushed to $s0 as seen in the result image above. – Ace NA Feb 29 '16 at 01:01
  • Make sure you examine the registers at the right point. With the `beq` in place that code doesn't do anything except load `$s0` with `1` and that should work no matter what. – Jester Feb 29 '16 at 01:31
  • I am not sure what you mean "the right point." What I am missing for my QtSpim is producing no results. – Ace NA Feb 29 '16 at 02:53
  • Okay I am now getting results. However, it is producing 1 more power value of n. For example, when n=3. The results are 16 instead of 8. Please see new question info above. – Ace NA Feb 29 '16 at 03:14
  • Well, that's to be expected since you initialize `$s0` with 2. `x << y` doesn't correspond to `x^y`, it corresponds to `x * (2^y)`, which is why you end up with the results you describe. – Michael Feb 29 '16 at 06:53