-2

I was working on a SPARC assembly program in which I call a subroutine called power which takes a base number and multiplies the base times its self based on the exponent. Essentially just calculating a power function. My problem is I am having trouble translating the following C function into SPARC assembly.

power(int base, int exponent)
{
    register int p, e;
    p = 1;

    for(int e=1; e <= exponent; e++)
    {
        p *= base;
    }
} 

This is what I have but I just get 49 as my answer:

 .global main

main: save %sp,-96,%sp
      mov 7,%i0
      mov 5,%i1
      mov 1,%l2
loop: mov %i0,%o0
      mov %i0,%o1
      call .mul
      nop
      cmp %l2,%i1
      ble loop
      dec %i1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Mickey
  • 3
  • 1
  • 2
    Clearly the answer should be 42. — Incidentally, that isn't a particularly good exponentiation algorithm, though if you mainly do squares and cubes, it won't matter much. For higher powers, you should be using an algorithm that is logarithmic in the power, not linear. – Jonathan Leffler Dec 02 '16 at 22:12
  • https://en.wikipedia.org/wiki/Exponentiation_by_squaring – phuclv Dec 04 '16 at 03:59

1 Answers1

0
.global main

main: save %sp,-96,%sp
      mov 7,%i0      ! base
      mov 5,%i1      ! exponent
      mov 1,%l2      ! p
      mov %l2,%o0    ! %o0 = p = 1
      cmp  %i1,0     
      ble  end       ! if (exponent <= 0) -> end
loop: mov %i0,%o1    ! %o1 = base
      call .mul      ! %o0 = %o0 * %o1 -> p = p * base
      nop
      cmp %l2,%i1
      bl loop
      dec %i1
end:

Changes to get the result (7⁵=16807):

  • Initalized %o0 with 1
  • Removed mov %i0,%o0 (every iteration you were smashing the mul result)
  • Replaced ble by bl
chus
  • 1,577
  • 15
  • 25