title: Assembly Power(A,b) function
body: <p>I'm trying to make an assembly power(a, b) function, based on this c code:</p>
  
  <pre><code>int power(int x, int y)
  {
      int z;
  
      z = 1;
      while (y &gt; 0) {
          if ((y % 2) == 1) {
              y = y - 1;
              z = z * x;
          } else {
              y = y / 2;
              x = x * x;
          }
      }
  
      return z;
  }
  </code></pre>
  
  <p>Though, for some reason, it only gets some outputs right, and I can't figure out where the problem is. Here is my assembly code:</p>
  
  <pre><code>;* int power(int x, int y);                                                  *
  ;*****************************************************************************
  %define y [ebp+12]
  %define x [ebp+8]
  %define z [ebp-4]
  
  
  
   power:
  push   ebp
  mov    ebp,esp
  sub    esp,16
  mov    byte[ebp-4], 1
  jmp    L3;
  
  L1:
  mov    eax,[ebp+12]
  and    eax,0x1
  test   eax,eax
  je     L2;
  sub    byte[ebp+12],1
  mov    eax,[ebp-4]
  imul   eax, [ebp+8]
  mov    [ebp-4],eax
  jmp    L3;
  
  L2:
  mov    eax,[ebp+12]
  mov    edx,eax
  shr    edx,31
   add    eax,edx
  sar    eax,1
   mov    [ebp+12],eax
  mov    eax,[ebp+8]
  imul   eax,[ebp+8]
  mov    [ebp+8],eax
  
  L3:
  cmp    byte[ebp+12],0
  jg     L1;
  mov    eax,[ebp-4]
  leave  
  ret 
  </code></pre>
  
  <p>When I run it, this is my output:</p>
  
  <pre><code>power(2, 0) returned -1217218303 - incorrect, should return 1
  power(2, 1) returned 2 - correct
  power(2, 2) returned -575029244 - incorrect, should return 4
  power(2, 3) returned 8 - correct
  </code></pre>
  
  <p>Could someone please help me figure out where I've gone wrong, or to correct my code, any help would be appreciated.</p>