-

2011年8月4日星期四

How do I implement a while loop with a counter in assembly code?

-I'm working with assembly code on a Linux machine and I want to repeat a while loop a number of times. I think I get the logic behind using a while loop with a counter in assembly but it just isn't working right.



Here's my code:



.section .data



msg: .ascii "A"

len: .int 1



.section .text

.global _start

_start:



movl $0, %eax



loop_begin:

cmpb $10, %al

jge loop_end





mov len, %edx

mov $msg, %ecx

mov $4, %eax

mov $1, %ebx

int $0x80

incb %al



jmp loop_begin



loop_end:



mov $0, %ebx

mov $1, %eax

int $0x80



Even if I change the incb %al to incb %bl, I keep getting an infinite loop of printing "A". I have even toyed with the jge loop_end to do jl or jle but the results never make sense in a way that shows the counter incrementing properly, but I just can't figure out what I'm missing.

Please help!Hi,



The problem is that AL is the low-order byte of EAX. Hence, when you do "mov $4, %eax" you also screw up your loop counter. You should use a different register for the counter, such as ESI or EDI.



Cheers,

Bogdanits so Simple...... write a while loop in a c program and compile using gcc wit -s option which generates .s file which contains assembly code for that c program... and you enjoy the code:)

for more info see man page of gcc

没有评论:

发表评论