简体   繁体   中英

Making a for loop in Assembly x86

I am new to Assembly and is wondering how I could write a for loop that will iterate 15 times. In the for loop i need to have an if condition that tests wether or not an integer k is greater than 7 as well. How would this be written in code?

Usually this would be written as a comment, but it is a little bit too complex. The code in the other answer isn't as efficient as it could be:

    MOV ECX, 15   ; number of iterations
.loop:
    ...
    CMP EAX, 8    ; compare k to 7
    DEC ECX          ; partial-flag merge needed after this, slow on some CPUs
    JA .loop      ; check for loop exit condition
B:                ; code after the loop
    ...
    ;; check CF here to see if k >= 8 or not, i.e. k > 7

EDIT: To have k in memory as 32-bit integer as before, the CMP instruction looks as the following:

    CMP DWORD [k], 8

EDIT2: Save one conditional jump. The OP didn't mention to leave or to stay when k is greater than 7. The above code leaves the loop when it ran 15 times or k isn't greater than 7.

Note that this trick with combining the comparisons is only likely to be good on CPUs like Intel Sandybridge-family or Silvermont which don't have partial-flag stalls for reading CF after a dec . On Core2 / Nehalem, this will stall for ~7 cycles to merge flags, like you'd get in an adc BigInteger loop using dec . See Agner Fog's microarch PDF .

Unless you're sure it's good on all the CPUs your code will run on, use cmp / ja or jae separately from dec / jnz .

EDIT3: The OP asks for incrementing/decrementing an integer (here edx) when eax is greater/smaller than 7:

.loop:
    ...
    CMP EAX, 7
    DEC EDX
    JB .end
    INC EDX
    JE .end
    INC EDX
.end:
    DEC ECX
    JZ .loop

(probably there'll be someone optimizing this further)

I suggest learning how to use compiled code to teach you such things. Write the code you want in C, then compile it with flags to output the assembly. For example, in gcc this is done with the -S flag. You can then read the machine-generated assembly code to see how it was accomplished.

The general strategy for a for-loop could be something like this:

       MOV ECX, 0    ; clear ECX
   A:    
       CMP [k], 7    ; compare k to 7
       JGT B         ; jump to B if k is greater than 7
       CMP ECX, 15   ; check for loop exit condition
       JE C          ; jump to C if we have iterated 15 times
       INC ECX
       JMP A
   B:            ; this happens if K is greater than 7
   ...
   C:            ; this happens if we reach the end of the loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM