tags:

views:

150

answers:

1

Hi, so I have the following assembly language code which I need to convert into C. I am confused on a few lines of the code.

I understand that this is a for loop. I have added my comments on each line.

I think the for loop goes like this

for (int i = 1; i > 0; i << what?) {
     //calculate result
 }

What is the test condition? And how to change i? I don't understand looking at the assembly code what the variable 'n' does?

This is Intel x86 so the format is movl = source, dest

  movl 8(%ebp), %esi     //get x
  movl 12(%ebp), %ebx    //get n
  movl $-1, %edi         //this should be result
  movl $1, %edx          //the i of the loop
.L2:
  movl %edx, %eax        
  andl %esi, %eax
  xorl %eax, %edi        //result = result ^ (i & x)
  movl %ebx, %ecx        //Why do we do this? As we never use $%ebx or %ecx again
  sall %cl, %edx         //Where did %cl come from?
  testl %edx, %edx       //tests if i != what? - condition of the for loop
  jne .L2                //loop again
  movl %edi, %eax        //otherwise return result.

Any help would be appreciated. Thank you

+6  A: 

sall %cl, %edx shifts %edx left by %cl bits. (%cl, for reference, is the low byte of %ecx.) The subsequent testl tests whether that shift zeroed out %edx.

The jne is called that because it's often used in the context of comparisons, which in ASM are often just subtractions. The flags would be set based on the difference; ZF would be set if the items are equal (since x - x == 0). It's also called jnz in Intel syntax; i'm not sure whether GNU allows that too.

All together, the three instructions translate to i <<= n; if (i != 0) goto L2;. That plus the label seem to make a for loop.

for (i = 1; i != 0; i <<= n) { result ^= i & x; }

Or, more correctly (but achieving the same goal), a do...while loop.

i = 1;
do { result ^= i & x; i <<= n; } while (i != 0);
cHao
Thank you! That was very helpful.
Catie