I want to convert simple loops in high-level languages into assembly language (for emu8086) say, I have this code:
for(int x = 0; x<=3; x++) { //Do something! }
or
int x=1; do{ //Do something! } while(x==1)
or
while(x==1){ //Do something }
How do I do this in emu8086?
The assembly language uses JMP instruction to implement loops. However, the processor set can use the LOOP instruction to implement loops conveniently.
Data Movement Instructions mov — Move (Opcodes: 88, 89, 8A, 8B, 8C, 8E, ...) The mov instruction copies the data item referred to by its second operand (i.e. register contents, memory contents, or a constant value) into the location referred to by its first operand (i.e. a register or memory).
For is entry controlled loop. While is also entry controlled loop. for ( init ; condition ; iteration ) { statement(s); } while ( condition ) { statement(s); } used to obtain the result only when number of iterations is known.
For-loop in C:
for(int x = 0; x<=3; x++) { //Do something! }
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0 loop1 nop ; Whatever you wanna do goes here, should not change cx inc cx ; Increment cmp cx,3 ; Compare cx to the limit jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations loop1 nop ; Whatever you wanna do goes here, should not change cx loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1; do{ //Do something! } while(x==1)
The same loop in assembler:
mov ax,1 loop1 nop ; Whatever you wanna do goes here cmp ax,1 ; Check wether cx is 1 je loop1 ; And loop if equal
While-loop in C:
while(x==1){ //Do something }
The same loop in assembler:
jmp loop1 ; Jump to condition first cloop1 nop ; Execute the content of the loop loop1 cmp ax,1 ; Check the condition je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With